blob: 160ffb3ee4460e5d5869b45b8705039f8543d7e0 [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 }
John Reckac09e452021-04-07 16:35:37 -0400570 float maxLuminance = layer->source.buffer.maxLuminanceNits;
571 // If the buffer doesn't have a max luminance, treat it as SDR & use the display's SDR
572 // white point
573 if (maxLuminance <= 0.f) {
574 maxLuminance = display.sdrWhitePointNits;
575 }
Ana Krulec47814212021-01-06 19:00:10 -0800576 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
John Reckac09e452021-04-07 16:35:37 -0400577 display.maxLuminance, maxLuminance);
Ana Krulec47814212021-01-06 19:00:10 -0800578 }
579 return shader;
580}
581
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500582void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500583 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500584 // Record display settings when capture is running.
585 std::stringstream displaySettings;
586 PrintTo(display, &displaySettings);
587 // Store the DisplaySettings in additional information.
588 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
589 SkData::MakeWithCString(displaySettings.str().c_str()));
590 }
591
592 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
593 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
594 // displays might have different scaling when compared to the physical screen.
595
596 canvas->clipRect(getSkRect(display.physicalDisplay));
597 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
598
599 const auto clipWidth = display.clip.width();
600 const auto clipHeight = display.clip.height();
601 auto rotatedClipWidth = clipWidth;
602 auto rotatedClipHeight = clipHeight;
603 // Scale is contingent on the rotation result.
604 if (display.orientation & ui::Transform::ROT_90) {
605 std::swap(rotatedClipWidth, rotatedClipHeight);
606 }
607 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
608 static_cast<SkScalar>(rotatedClipWidth);
609 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
610 static_cast<SkScalar>(rotatedClipHeight);
611 canvas->scale(scaleX, scaleY);
612
613 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
614 // back so that the top left corner of the clip is at (0, 0).
615 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
616 canvas->rotate(toDegrees(display.orientation));
617 canvas->translate(-clipWidth / 2, -clipHeight / 2);
618 canvas->translate(-display.clip.left, -display.clip.top);
619}
620
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500621class AutoSaveRestore {
622public:
623 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
624 ~AutoSaveRestore() { restore(); }
625 void replace(SkCanvas* canvas) {
626 mCanvas = canvas;
627 mSaveCount = canvas->save();
628 }
629 void restore() {
630 if (mCanvas) {
631 mCanvas->restoreToCount(mSaveCount);
632 mCanvas = nullptr;
633 }
634 }
635
636private:
637 SkCanvas* mCanvas;
638 int mSaveCount;
639};
640
John Reck67b1e2b2020-08-26 13:17:24 -0700641status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
642 const std::vector<const LayerSettings*>& layers,
Alec Mouria90a5702021-04-16 16:36:21 +0000643 const std::shared_ptr<ExternalTexture>& buffer,
644 const bool /*useFramebufferCache*/,
John Reck67b1e2b2020-08-26 13:17:24 -0700645 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
646 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800647
John Reck67b1e2b2020-08-26 13:17:24 -0700648 std::lock_guard<std::mutex> lock(mRenderingMutex);
649 if (layers.empty()) {
650 ALOGV("Drawing empty layer stack");
651 return NO_ERROR;
652 }
653
654 if (bufferFence.get() >= 0) {
655 // Duplicate the fence for passing to waitFence.
656 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
657 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
658 ATRACE_NAME("Waiting before draw");
659 sync_wait(bufferFence.get(), -1);
660 }
661 }
662 if (buffer == nullptr) {
663 ALOGE("No output buffer provided. Aborting GPU composition.");
664 return BAD_VALUE;
665 }
666
Alec Mouria90a5702021-04-16 16:36:21 +0000667 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800668
Lucas Dupind508e472020-11-04 04:32:06 +0000669 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800670 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700671
Alec Mouria90a5702021-04-16 16:36:21 +0000672 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
673 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
674 surfaceTextureRef = it->second;
675 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400676 surfaceTextureRef =
677 std::make_shared<AutoBackendTexture::LocalRef>(grContext.get(),
678 buffer->getBuffer()
679 ->toAHardwareBuffer(),
680 true);
John Reck67b1e2b2020-08-26 13:17:24 -0700681 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800682
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500683 const ui::Dataspace dstDataspace =
684 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500685 sk_sp<SkSurface> dstSurface =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400686 surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700687
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500688 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
689 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800690 ALOGE("Cannot acquire canvas from Skia.");
691 return BAD_VALUE;
692 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500693
694 // Find if any layers have requested blur, we'll use that info to decide when to render to an
695 // offscreen buffer and when to render to the native buffer.
696 sk_sp<SkSurface> activeSurface(dstSurface);
697 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500698 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500699 const LayerSettings* blurCompositionLayer = nullptr;
700 if (mBlurFilter) {
701 bool requiresCompositionLayer = false;
702 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500703 if (layer->backgroundBlurRadius > 0 &&
704 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500705 requiresCompositionLayer = true;
706 }
707 for (auto region : layer->blurRegions) {
708 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
709 requiresCompositionLayer = true;
710 }
711 }
712 if (requiresCompositionLayer) {
713 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500714 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500715 blurCompositionLayer = layer;
716 break;
717 }
718 }
719 }
720
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500721 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700722 // Clear the entire canvas with a transparent black to prevent ghost images.
723 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500724 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800725
726 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
727 // view is still on-screen. The clear region could be re-specified as a black color layer,
728 // however.
729 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500730 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800731 size_t numRects = 0;
732 Rect const* rects = display.clearRegion.getArray(&numRects);
733 SkIRect skRects[numRects];
734 for (int i = 0; i < numRects; ++i) {
735 skRects[i] =
736 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
737 }
738 SkRegion clearRegion;
739 SkPaint paint;
740 sk_sp<SkShader> shader =
741 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500742 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800743 paint.setShader(shader);
744 clearRegion.setRects(skRects, numRects);
745 canvas->drawRegion(clearRegion, paint);
746 }
747
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500748 // setup color filter if necessary
749 sk_sp<SkColorFilter> displayColorTransform;
750 if (display.colorTransform != mat4()) {
751 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
752 }
753
John Reck67b1e2b2020-08-26 13:17:24 -0700754 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500755 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100756
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400757 if (kPrintLayerSettings) {
758 std::stringstream ls;
759 PrintTo(*layer, &ls);
760 auto debugs = ls.str();
761 int pos = 0;
762 while (pos < debugs.size()) {
763 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
764 pos += 1000;
765 }
766 }
767
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500768 sk_sp<SkImage> blurInput;
769 if (blurCompositionLayer == layer) {
770 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
771 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
772
773 // save a snapshot of the activeSurface to use as input to the blur shaders
774 blurInput = activeSurface->makeImageSnapshot();
775
776 // TODO we could skip this step if we know the blur will cover the entire image
777 // blit the offscreen framebuffer into the destination AHB
778 SkPaint paint;
779 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500780 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
781 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
782 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
783 String8::format("SurfaceID|%" PRId64, id).c_str(),
784 nullptr);
785 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
786 } else {
787 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
788 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500789
790 // assign dstCanvas to canvas and ensure that the canvas state is up to date
791 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500792 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500793 initCanvas(canvas, display);
794
795 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
796 dstSurface->getCanvas()->getSaveCount());
797 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
798 dstSurface->getCanvas()->getTotalMatrix());
799
800 // assign dstSurface to activeSurface
801 activeSurface = dstSurface;
802 }
803
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500804 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500805 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800806 // Record the name of the layer if the capture is running.
807 std::stringstream layerSettings;
808 PrintTo(*layer, &layerSettings);
809 // Store the LayerSettings in additional information.
810 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
811 SkData::MakeWithCString(layerSettings.str().c_str()));
812 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100813 // Layers have a local transform that should be applied to them
814 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100815
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500816 const auto bounds = getSkRect(layer->geometry.boundaries);
817 if (mBlurFilter && layerHasBlur(layer)) {
818 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
819
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500820 // if multiple layers have blur, then we need to take a snapshot now because
821 // only the lowest layer will have blurImage populated earlier
822 if (!blurInput) {
823 blurInput = activeSurface->makeImageSnapshot();
824 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500825 // rect to be blurred in the coordinate space of blurInput
826 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
827
Galia Peychevae425ac82021-03-15 17:12:03 +0100828 // TODO(b/182216890): Filter out empty layers earlier
829 if (blurRect.width() > 0 && blurRect.height() > 0) {
830 if (layer->backgroundBlurRadius > 0) {
831 ATRACE_NAME("BackgroundBlur");
832 auto blurredImage =
833 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
834 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100835
Galia Peychevae425ac82021-03-15 17:12:03 +0100836 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500837
Galia Peychevae425ac82021-03-15 17:12:03 +0100838 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect,
839 blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700840 }
Derek Sollenberger39feade2021-04-27 16:08:40 -0400841 SkAutoCanvasRestore acr(canvas, true);
842 canvas->concat(getSkM44(layer->blurRegionTransform).asM33());
Galia Peychevae425ac82021-03-15 17:12:03 +0100843 for (auto region : layer->blurRegions) {
844 if (cachedBlurs[region.blurRadius] == nullptr) {
845 ATRACE_NAME("BlurRegion");
846 cachedBlurs[region.blurRadius] =
847 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
848 blurRect);
849 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500850
Galia Peychevae425ac82021-03-15 17:12:03 +0100851 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
852 cachedBlurs[region.blurRadius], blurInput);
853 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700854 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700855 }
856
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500857 // Shadows are assumed to live only on their own layer - it's not valid
858 // to draw the boundary rectangles when there is already a caster shadow
859 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
860 // composition - using a well-defined invalid color is long-term less error-prone.
861 if (layer->shadow.length > 0) {
862 const auto rect = layer->geometry.roundedCornersRadius > 0
863 ? getSkRect(layer->geometry.roundedCornersCrop)
864 : bounds;
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400865 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
866 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500867 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
868 continue;
869 }
870
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500871 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
872 (mUseColorManagement &&
John Reckac09e452021-04-07 16:35:37 -0400873 needsToneMapping(layer->sourceDataspace, display.outputDataspace)) ||
874 (display.sdrWhitePointNits > 0.f &&
875 display.sdrWhitePointNits != display.maxLuminance);
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500876
877 // quick abort from drawing the remaining portion of the layer
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400878 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500879 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
880 continue;
881 }
882
883 // If we need to map to linear space or color management is disabled, then mark the source
884 // image with the same colorspace as the destination surface so that Skia's color
885 // management is a no-op.
886 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
887 ? dstDataspace
888 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800889
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500890 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700891 if (layer->source.buffer.buffer) {
892 ATRACE_NAME("DrawImage");
Alec Mouria90a5702021-04-16 16:36:21 +0000893 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700894 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800895 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000896
897 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
898 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800899 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700900 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000901 // If we didn't find the image in the cache, then create a local ref but don't cache
902 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
903 // we didn't find anything in the cache then we intentionally did not cache this
904 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400905 imageTextureRef = std::make_shared<
906 AutoBackendTexture::LocalRef>(grContext.get(),
907 item.buffer->getBuffer()->toAHardwareBuffer(),
908 false);
John Reck67b1e2b2020-08-26 13:17:24 -0700909 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800910
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800911 sk_sp<SkImage> image =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400912 imageTextureRef->makeImage(layerDataspace,
913 item.usePremultipliedAlpha ? kPremul_SkAlphaType
914 : kUnpremul_SkAlphaType,
915 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700916
917 auto texMatrix = getSkM44(item.textureTransform).asM33();
918 // textureTansform was intended to be passed directly into a shader, so when
919 // building the total matrix with the textureTransform we need to first
920 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500921 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800922 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700923
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800924 SkMatrix matrix;
925 if (!texMatrix.invert(&matrix)) {
926 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700927 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800928 // The shader does not respect the translation, so we add it to the texture
929 // transform for the SkImage. This will make sure that the correct layer contents
930 // are drawn in the correct part of the screen.
931 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700932
Ana Krulecb7b28b22020-11-23 14:48:58 -0800933 sk_sp<SkShader> shader;
934
935 if (layer->source.buffer.useTextureFiltering) {
936 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
937 SkSamplingOptions(
938 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
939 &matrix);
940 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500941 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800942 }
Alec Mouri029d1952020-10-12 10:37:08 -0700943
Alec Mouric0aae732021-01-12 13:32:18 -0800944 // Handle opaque images - it's a little nonstandard how we do this.
945 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
946 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
947 // The important language is that when isOpaque is set, opacity is not sampled from the
948 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
949 // here's the conundrum:
950 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
951 // as an internal hint - composition is undefined when there are alpha bits present.
952 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
953 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
954 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
955 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
956 // of a hack anyways.
957 // 3. We can't change the blendmode to src, because while this satisfies the requirement
958 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
959 // because src always clobbers the destination content.
960 //
961 // So, what we do here instead is an additive blend mode where we compose the input
962 // image with a solid black. This might need to be reassess if this does not support
963 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
964 if (item.isOpaque) {
965 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
966 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500967 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800968 }
969
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500970 paint.setShader(createRuntimeEffectShader(shader, layer, display,
971 !item.isOpaque && item.usePremultipliedAlpha,
972 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800973 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700974 } else {
975 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700976 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800977 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
978 .fG = color.g,
979 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800980 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500981 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800982 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500983 /* undoPremultipliedAlpha */ false,
984 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700985 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700986
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400987 if (layer->disableBlending) {
988 paint.setBlendMode(SkBlendMode::kSrc);
989 }
990
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500991 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700992
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500993 if (layer->geometry.roundedCornersRadius > 0) {
994 paint.setAntiAlias(true);
995 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800996 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500997 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700998 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400999 if (kFlushAfterEveryLayer) {
1000 ATRACE_NAME("flush surface");
1001 activeSurface->flush();
1002 }
John Reck67b1e2b2020-08-26 13:17:24 -07001003 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001004 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001005 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001006 {
1007 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001008 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1009 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001010 }
1011
1012 if (drawFence != nullptr) {
1013 *drawFence = flush();
1014 }
1015
1016 // If flush failed or we don't support native fences, we need to force the
1017 // gl command stream to be executed.
1018 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1019 if (requireSync) {
1020 ATRACE_BEGIN("Submit(sync=true)");
1021 } else {
1022 ATRACE_BEGIN("Submit(sync=false)");
1023 }
Lucas Dupind508e472020-11-04 04:32:06 +00001024 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001025 ATRACE_END();
1026 if (!success) {
1027 ALOGE("Failed to flush RenderEngine commands");
1028 // Chances are, something illegal happened (either the caller passed
1029 // us bad parameters, or we messed up our shader generation).
1030 return INVALID_OPERATION;
1031 }
1032
1033 // checkErrors();
1034 return NO_ERROR;
1035}
1036
Lucas Dupin3f11e922020-09-22 17:31:04 -07001037inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1038 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1039}
1040
1041inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1042 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1043}
1044
Lucas Dupin21f348e2020-09-16 17:31:26 -07001045inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -08001046 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001047 const auto cornerRadius = layer->geometry.roundedCornersRadius;
1048 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
1049}
1050
Galia Peycheva80116e52020-11-06 11:57:25 +01001051inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
1052 const auto rect = getSkRect(layer->geometry.boundaries);
1053 const auto cornersRadius = layer->geometry.roundedCornersRadius;
1054 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
1055 .cornerRadiusTL = cornersRadius,
1056 .cornerRadiusTR = cornersRadius,
1057 .cornerRadiusBL = cornersRadius,
1058 .cornerRadiusBR = cornersRadius,
1059 .alpha = 1,
1060 .left = static_cast<int>(rect.fLeft),
1061 .top = static_cast<int>(rect.fTop),
1062 .right = static_cast<int>(rect.fRight),
1063 .bottom = static_cast<int>(rect.fBottom)};
1064}
1065
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001066inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
1067 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
1068}
1069
Lucas Dupin3f11e922020-09-22 17:31:04 -07001070inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1071 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1072}
1073
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001074inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1075 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1076 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1077 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1078 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1079}
1080
Lucas Dupin3f11e922020-09-22 17:31:04 -07001081inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1082 return SkPoint3::Make(vector.x, vector.y, vector.z);
1083}
1084
John Reck67b1e2b2020-08-26 13:17:24 -07001085size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1086 return mGrContext->maxTextureSize();
1087}
1088
1089size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1090 return mGrContext->maxRenderTargetSize();
1091}
1092
Lucas Dupin3f11e922020-09-22 17:31:04 -07001093void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1094 const ShadowSettings& settings) {
1095 ATRACE_CALL();
1096 const float casterZ = settings.length / 2.0f;
1097 const auto shadowShape = cornerRadius > 0
1098 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1099 : SkPath::Rect(casterRect);
1100 const auto flags =
1101 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1102
1103 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1104 getSkPoint3(settings.lightPos), settings.lightRadius,
1105 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1106 flags);
1107}
1108
John Reck67b1e2b2020-08-26 13:17:24 -07001109EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001110 EGLContext shareContext,
1111 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001112 Protection protection) {
1113 EGLint renderableType = 0;
1114 if (config == EGL_NO_CONFIG_KHR) {
1115 renderableType = EGL_OPENGL_ES3_BIT;
1116 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1117 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1118 }
1119 EGLint contextClientVersion = 0;
1120 if (renderableType & EGL_OPENGL_ES3_BIT) {
1121 contextClientVersion = 3;
1122 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1123 contextClientVersion = 2;
1124 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1125 contextClientVersion = 1;
1126 } else {
1127 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1128 }
1129
1130 std::vector<EGLint> contextAttributes;
1131 contextAttributes.reserve(7);
1132 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1133 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001134 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001135 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001136 switch (*contextPriority) {
1137 case ContextPriority::REALTIME:
1138 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1139 break;
1140 case ContextPriority::MEDIUM:
1141 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1142 break;
1143 case ContextPriority::LOW:
1144 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1145 break;
1146 case ContextPriority::HIGH:
1147 default:
1148 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1149 break;
1150 }
John Reck67b1e2b2020-08-26 13:17:24 -07001151 }
1152 if (protection == Protection::PROTECTED) {
1153 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1154 contextAttributes.push_back(EGL_TRUE);
1155 }
1156 contextAttributes.push_back(EGL_NONE);
1157
1158 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1159
1160 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1161 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1162 // EGL_NO_CONTEXT so that we can abort.
1163 if (config != EGL_NO_CONFIG_KHR) {
1164 return context;
1165 }
1166 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1167 // should try to fall back to GLES 2.
1168 contextAttributes[1] = 2;
1169 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1170 }
1171
1172 return context;
1173}
1174
Alec Mourid6f09462020-12-07 11:18:17 -08001175std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1176 const RenderEngineCreationArgs& args) {
1177 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1178 return std::nullopt;
1179 }
1180
1181 switch (args.contextPriority) {
1182 case RenderEngine::ContextPriority::REALTIME:
1183 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1184 return RenderEngine::ContextPriority::REALTIME;
1185 } else {
1186 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1187 return RenderEngine::ContextPriority::HIGH;
1188 }
1189 case RenderEngine::ContextPriority::HIGH:
1190 case RenderEngine::ContextPriority::MEDIUM:
1191 case RenderEngine::ContextPriority::LOW:
1192 return args.contextPriority;
1193 default:
1194 return std::nullopt;
1195 }
1196}
1197
John Reck67b1e2b2020-08-26 13:17:24 -07001198EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1199 EGLConfig config, int hwcFormat,
1200 Protection protection) {
1201 EGLConfig placeholderConfig = config;
1202 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1203 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1204 }
1205 std::vector<EGLint> attributes;
1206 attributes.reserve(7);
1207 attributes.push_back(EGL_WIDTH);
1208 attributes.push_back(1);
1209 attributes.push_back(EGL_HEIGHT);
1210 attributes.push_back(1);
1211 if (protection == Protection::PROTECTED) {
1212 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1213 attributes.push_back(EGL_TRUE);
1214 }
1215 attributes.push_back(EGL_NONE);
1216
1217 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1218}
1219
Alec Mourid6f09462020-12-07 11:18:17 -08001220int SkiaGLRenderEngine::getContextPriority() {
1221 int value;
1222 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1223 return value;
1224}
1225
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001226void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1227 // This cache multiplier was selected based on review of cache sizes relative
1228 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1229 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1230 // conservative default based on that analysis.
1231 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1232 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1233
1234 // start by resizing the current context
1235 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1236 grContext->setResourceCacheLimit(maxResourceBytes);
1237
1238 // if it is possible to switch contexts then we will resize the other context
1239 if (useProtectedContext(!mInProtectedContext)) {
1240 grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1241 grContext->setResourceCacheLimit(maxResourceBytes);
1242 // reset back to the initial context that was active when this method was called
1243 useProtectedContext(!mInProtectedContext);
1244 }
1245}
1246
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001247void SkiaGLRenderEngine::dump(std::string& result) {
1248 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1249
1250 StringAppendF(&result, "\n ------------RE-----------------\n");
1251 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1252 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1253 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1254 extensions.getVersion());
1255 StringAppendF(&result, "%s\n", extensions.getExtensions());
1256 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1257 supportsProtectedContent());
1258 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001259 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1260 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001261
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001262 std::vector<ResourcePair> cpuResourceMap = {
1263 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1264 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1265 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1266 {"skia/sk_resource_cache/tessellated", "Shadows"},
1267 {"skia", "Other"},
1268 };
1269 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1270 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1271 StringAppendF(&result, "Skia CPU Caches: ");
1272 cpuReporter.logTotals(result);
1273 cpuReporter.logOutput(result);
1274
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001275 {
1276 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001277
1278 std::vector<ResourcePair> gpuResourceMap = {
1279 {"texture_renderbuffer", "Texture/RenderBuffer"},
1280 {"texture", "Texture"},
1281 {"gr_text_blob_cache", "Text"},
1282 {"skia", "Other"},
1283 };
1284 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1285 mGrContext->dumpMemoryStatistics(&gpuReporter);
1286 StringAppendF(&result, "Skia's GPU Caches: ");
1287 gpuReporter.logTotals(result);
1288 gpuReporter.logOutput(result);
1289 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1290 gpuReporter.logOutput(result, true);
1291
Alec Mouria90a5702021-04-16 16:36:21 +00001292 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1293 mGraphicBufferExternalRefs.size());
1294 StringAppendF(&result, "Dumping buffer ids...\n");
1295 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1296 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1297 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001298 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1299 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001300 StringAppendF(&result, "Dumping buffer ids...\n");
1301 // TODO(178539829): It would be nice to know which layer these are coming from and what
1302 // the texture sizes are.
1303 for (const auto& [id, unused] : mTextureCache) {
1304 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1305 }
1306 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001307
1308 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001309 if (mProtectedGrContext) {
1310 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1311 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001312 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1313 gpuProtectedReporter.logTotals(result);
1314 gpuProtectedReporter.logOutput(result);
1315 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1316 gpuProtectedReporter.logOutput(result, true);
1317
1318 StringAppendF(&result, "RenderEngine protected AHB/BackendTexture cache size: %zu\n",
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001319 mProtectedTextureCache.size());
1320 StringAppendF(&result, "Dumping buffer ids...\n");
1321 for (const auto& [id, unused] : mProtectedTextureCache) {
1322 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1323 }
1324 StringAppendF(&result, "\n");
1325 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1326 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1327 StringAppendF(&result, "- inputDataspace: %s\n",
1328 dataspaceDetails(
1329 static_cast<android_dataspace>(linearEffect.inputDataspace))
1330 .c_str());
1331 StringAppendF(&result, "- outputDataspace: %s\n",
1332 dataspaceDetails(
1333 static_cast<android_dataspace>(linearEffect.outputDataspace))
1334 .c_str());
1335 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1336 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1337 }
1338 }
1339 StringAppendF(&result, "\n");
1340}
1341
John Reck67b1e2b2020-08-26 13:17:24 -07001342} // namespace skia
1343} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001344} // namespace android