blob: fb7e2856e4c1f6645e5d0d72f84dac488516bca4 [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>
John Reck67b1e2b2020-08-26 13:17:24 -070031#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070032#include <SkImageFilters.h>
Alec Mouric0aae732021-01-12 13:32:18 -080033#include <SkRegion.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070034#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070035#include <SkSurface.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080036#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070037#include <gl/GrGLInterface.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080038#include <sync/sync.h>
39#include <ui/BlurRegion.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080040#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080041#include <ui/GraphicBuffer.h>
42#include <utils/Trace.h>
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -050043#include "Cache.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"
Alec Mouric0aae732021-01-12 13:32:18 -080050#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080051#include "SkBlendMode.h"
52#include "SkImageInfo.h"
53#include "filters/BlurFilter.h"
54#include "filters/LinearEffect.h"
55#include "log/log_main.h"
56#include "skia/debug/SkiaCapture.h"
57#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070058
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040059namespace {
60// Debugging settings
61static const bool kPrintLayerSettings = false;
62static const bool kFlushAfterEveryLayer = false;
63} // namespace
64
John Reck67b1e2b2020-08-26 13:17:24 -070065bool checkGlError(const char* op, int lineNumber);
66
67namespace android {
68namespace renderengine {
69namespace skia {
70
Ana Krulec1d12b3b2021-01-27 16:49:51 -080071using base::StringAppendF;
72
John Reck67b1e2b2020-08-26 13:17:24 -070073static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
74 EGLint wanted, EGLConfig* outConfig) {
75 EGLint numConfigs = -1, n = 0;
76 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
77 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
78 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
79 configs.resize(n);
80
81 if (!configs.empty()) {
82 if (attribute != EGL_NONE) {
83 for (EGLConfig config : configs) {
84 EGLint value = 0;
85 eglGetConfigAttrib(dpy, config, attribute, &value);
86 if (wanted == value) {
87 *outConfig = config;
88 return NO_ERROR;
89 }
90 }
91 } else {
92 // just pick the first one
93 *outConfig = configs[0];
94 return NO_ERROR;
95 }
96 }
97
98 return NAME_NOT_FOUND;
99}
100
101static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
102 EGLConfig* config) {
103 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
104 // it is to be used with WIFI displays
105 status_t err;
106 EGLint wantedAttribute;
107 EGLint wantedAttributeValue;
108
109 std::vector<EGLint> attribs;
110 if (renderableType) {
111 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
112 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
113
114 // Default to 8 bits per channel.
115 const EGLint tmpAttribs[] = {
116 EGL_RENDERABLE_TYPE,
117 renderableType,
118 EGL_RECORDABLE_ANDROID,
119 EGL_TRUE,
120 EGL_SURFACE_TYPE,
121 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
122 EGL_FRAMEBUFFER_TARGET_ANDROID,
123 EGL_TRUE,
124 EGL_RED_SIZE,
125 is1010102 ? 10 : 8,
126 EGL_GREEN_SIZE,
127 is1010102 ? 10 : 8,
128 EGL_BLUE_SIZE,
129 is1010102 ? 10 : 8,
130 EGL_ALPHA_SIZE,
131 is1010102 ? 2 : 8,
132 EGL_NONE,
133 };
134 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
135 std::back_inserter(attribs));
136 wantedAttribute = EGL_NONE;
137 wantedAttributeValue = EGL_NONE;
138 } else {
139 // if no renderable type specified, fallback to a simplified query
140 wantedAttribute = EGL_NATIVE_VISUAL_ID;
141 wantedAttributeValue = format;
142 }
143
144 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
145 config);
146 if (err == NO_ERROR) {
147 EGLint caveat;
148 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
149 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
150 }
151
152 return err;
153}
154
155std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
156 const RenderEngineCreationArgs& args) {
157 // initialize EGL for the default display
158 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
159 if (!eglInitialize(display, nullptr, nullptr)) {
160 LOG_ALWAYS_FATAL("failed to initialize EGL");
161 }
162
Yiwei Zhange2650962020-12-01 23:27:58 +0000163 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700164 if (!eglVersion) {
165 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000166 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700167 }
168
Yiwei Zhange2650962020-12-01 23:27:58 +0000169 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700170 if (!eglExtensions) {
171 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000172 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700173 }
174
175 auto& extensions = gl::GLExtensions::getInstance();
176 extensions.initWithEGLStrings(eglVersion, eglExtensions);
177
178 // The code assumes that ES2 or later is available if this extension is
179 // supported.
180 EGLConfig config = EGL_NO_CONFIG_KHR;
181 if (!extensions.hasNoConfigContext()) {
182 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
183 }
184
John Reck67b1e2b2020-08-26 13:17:24 -0700185 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800186 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700187 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800188 protectedContext =
189 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700190 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
191 }
192
Alec Mourid6f09462020-12-07 11:18:17 -0800193 EGLContext ctxt =
194 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700195
196 // if can't create a GL context, we can only abort.
197 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
198
199 EGLSurface placeholder = EGL_NO_SURFACE;
200 if (!extensions.hasSurfacelessContext()) {
201 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
202 Protection::UNPROTECTED);
203 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
204 }
205 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
206 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
207 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
208 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
209
210 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
211 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
212 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
213 Protection::PROTECTED);
214 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
215 "can't create protected placeholder pbuffer");
216 }
217
218 // initialize the renderer while GL is current
219 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000220 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
221 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700222
223 ALOGI("OpenGL ES informations:");
224 ALOGI("vendor : %s", extensions.getVendor());
225 ALOGI("renderer : %s", extensions.getRenderer());
226 ALOGI("version : %s", extensions.getVersion());
227 ALOGI("extensions: %s", extensions.getExtensions());
228 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
229 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
230
231 return engine;
232}
233
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500234void SkiaGLRenderEngine::primeCache() {
235 Cache::primeShaderCache(this);
236}
237
John Reck67b1e2b2020-08-26 13:17:24 -0700238EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
239 status_t err;
240 EGLConfig config;
241
242 // First try to get an ES3 config
243 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
244 if (err != NO_ERROR) {
245 // If ES3 fails, try to get an ES2 config
246 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
247 if (err != NO_ERROR) {
248 // If ES2 still doesn't work, probably because we're on the emulator.
249 // try a simplified query
250 ALOGW("no suitable EGLConfig found, trying a simpler query");
251 err = selectEGLConfig(display, format, 0, &config);
252 if (err != NO_ERROR) {
253 // this EGL is too lame for android
254 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
255 }
256 }
257 }
258
259 if (logConfig) {
260 // print some debugging info
261 EGLint r, g, b, a;
262 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
263 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
264 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
265 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
266 ALOGI("EGL information:");
267 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
268 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
269 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
270 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
271 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
272 }
273
274 return config;
275}
276
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400277sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
278 // This "cache" does not actually cache anything. It just allows us to
279 // monitor Skia's internal cache. So this method always returns null.
280 return nullptr;
281}
282
283void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
284 const SkString& description) {
285 mShadersCachedSinceLastCall++;
286}
287
288void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
289 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
290 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
291 numShaders, cached);
292}
293
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400294int SkiaGLRenderEngine::reportShadersCompiled() {
295 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
296}
297
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700298SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000299 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700300 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800301 : SkiaRenderEngine(args.renderEngineType),
302 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700303 mEGLContext(ctxt),
304 mPlaceholderSurface(placeholder),
305 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700306 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400307 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800308 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700309 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
310 LOG_ALWAYS_FATAL_IF(!glInterface.get());
311
312 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400313 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700314 options.fDisableDistanceFieldPaths = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400315 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000316 mGrContext = GrDirectContext::MakeGL(glInterface, options);
317 if (useProtectedContext(true)) {
318 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
319 useProtectedContext(false);
320 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700321
322 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500323 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700324 mBlurFilter = new BlurFilter();
325 }
Alec Mouric0aae732021-01-12 13:32:18 -0800326 mCapture = std::make_unique<SkiaCapture>();
327}
328
329SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100330 cleanFramebufferCache();
Alec Mouric0aae732021-01-12 13:32:18 -0800331
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
Ana Krulecdfec8f52021-01-13 12:51:47 -0800485void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
486 // Only run this if RE is running on its own thread. This way the access to GL
487 // operations is guaranteed to be happening on the same thread.
488 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
489 return;
490 }
491 ATRACE_CALL();
492
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400493 // We need to switch the currently bound context if the buffer is protected but the current
494 // context is not. The current state must then be restored after the buffer is cached.
495 const bool protectedContextState = mInProtectedContext;
496 if (!useProtectedContext(protectedContextState ||
497 (buffer->getUsage() & GRALLOC_USAGE_PROTECTED))) {
498 ALOGE("Attempting to cache a buffer into a different context than what is currently bound");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800499 return;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400500 }
501
502 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
503 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
504
505 std::lock_guard<std::mutex> lock(mRenderingMutex);
506 auto iter = cache.find(buffer->getId());
507 if (iter != cache.end()) {
508 ALOGV("Texture already exists in cache.");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800509 } else {
510 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
511 std::make_shared<AutoBackendTexture::LocalRef>();
512 imageTextureRef->setTexture(
Derek Sollenberger34257882021-04-06 18:32:34 +0000513 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), false));
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
John Reck67b1e2b2020-08-26 13:17:24 -0700520void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
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 Mouric7f6c8b2020-11-09 18:35:20 -0800523 mTextureCache.erase(bufferId);
524 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700525}
526
Ana Krulec47814212021-01-06 19:00:10 -0800527sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
528 const LayerSettings* layer,
529 const DisplaySettings& display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500530 bool undoPremultipliedAlpha,
531 bool requiresLinearEffect) {
John Reckcdb4ed72021-02-04 13:39:33 -0500532 if (layer->stretchEffect.hasEffect()) {
533 // TODO: Implement
534 }
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500535 if (requiresLinearEffect) {
536 const ui::Dataspace inputDataspace =
537 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
538 const ui::Dataspace outputDataspace =
539 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
540
541 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
542 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800543 .undoPremultipliedAlpha = undoPremultipliedAlpha};
544
545 auto effectIter = mRuntimeEffects.find(effect);
546 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
547 if (effectIter == mRuntimeEffects.end()) {
548 runtimeEffect = buildRuntimeEffect(effect);
549 mRuntimeEffects.insert({effect, runtimeEffect});
550 } else {
551 runtimeEffect = effectIter->second;
552 }
553 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
554 display.maxLuminance,
555 layer->source.buffer.maxMasteringLuminance,
556 layer->source.buffer.maxContentLuminance);
557 }
558 return shader;
559}
560
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500561void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500562 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500563 // Record display settings when capture is running.
564 std::stringstream displaySettings;
565 PrintTo(display, &displaySettings);
566 // Store the DisplaySettings in additional information.
567 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
568 SkData::MakeWithCString(displaySettings.str().c_str()));
569 }
570
571 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
572 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
573 // displays might have different scaling when compared to the physical screen.
574
575 canvas->clipRect(getSkRect(display.physicalDisplay));
576 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
577
578 const auto clipWidth = display.clip.width();
579 const auto clipHeight = display.clip.height();
580 auto rotatedClipWidth = clipWidth;
581 auto rotatedClipHeight = clipHeight;
582 // Scale is contingent on the rotation result.
583 if (display.orientation & ui::Transform::ROT_90) {
584 std::swap(rotatedClipWidth, rotatedClipHeight);
585 }
586 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
587 static_cast<SkScalar>(rotatedClipWidth);
588 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
589 static_cast<SkScalar>(rotatedClipHeight);
590 canvas->scale(scaleX, scaleY);
591
592 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
593 // back so that the top left corner of the clip is at (0, 0).
594 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
595 canvas->rotate(toDegrees(display.orientation));
596 canvas->translate(-clipWidth / 2, -clipHeight / 2);
597 canvas->translate(-display.clip.left, -display.clip.top);
598}
599
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500600class AutoSaveRestore {
601public:
602 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
603 ~AutoSaveRestore() { restore(); }
604 void replace(SkCanvas* canvas) {
605 mCanvas = canvas;
606 mSaveCount = canvas->save();
607 }
608 void restore() {
609 if (mCanvas) {
610 mCanvas->restoreToCount(mSaveCount);
611 mCanvas = nullptr;
612 }
613 }
614
615private:
616 SkCanvas* mCanvas;
617 int mSaveCount;
618};
619
John Reck67b1e2b2020-08-26 13:17:24 -0700620status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
621 const std::vector<const LayerSettings*>& layers,
622 const sp<GraphicBuffer>& buffer,
623 const bool useFramebufferCache,
624 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
625 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800626
John Reck67b1e2b2020-08-26 13:17:24 -0700627 std::lock_guard<std::mutex> lock(mRenderingMutex);
628 if (layers.empty()) {
629 ALOGV("Drawing empty layer stack");
630 return NO_ERROR;
631 }
632
633 if (bufferFence.get() >= 0) {
634 // Duplicate the fence for passing to waitFence.
635 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
636 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
637 ATRACE_NAME("Waiting before draw");
638 sync_wait(bufferFence.get(), -1);
639 }
640 }
641 if (buffer == nullptr) {
642 ALOGE("No output buffer provided. Aborting GPU composition.");
643 return BAD_VALUE;
644 }
645
Ady Abraham193426d2021-02-18 14:01:53 -0800646 validateOutputBufferUsage(buffer);
647
Lucas Dupind508e472020-11-04 04:32:06 +0000648 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800649 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700650 AHardwareBuffer_Desc bufferDesc;
651 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700652
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800653 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700654 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000655 auto iter = cache.find(buffer->getId());
656 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700657 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800658 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800659 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700660 }
661 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800662
663 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800664 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800665 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
666 surfaceTextureRef->setTexture(
Derek Sollenberger34257882021-04-06 18:32:34 +0000667 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800668 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700669 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800670 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700671 }
672 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800673
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500674 const ui::Dataspace dstDataspace =
675 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500676 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500677 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700678
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500679 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
680 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800681 ALOGE("Cannot acquire canvas from Skia.");
682 return BAD_VALUE;
683 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500684
685 // Find if any layers have requested blur, we'll use that info to decide when to render to an
686 // offscreen buffer and when to render to the native buffer.
687 sk_sp<SkSurface> activeSurface(dstSurface);
688 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500689 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500690 const LayerSettings* blurCompositionLayer = nullptr;
691 if (mBlurFilter) {
692 bool requiresCompositionLayer = false;
693 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500694 if (layer->backgroundBlurRadius > 0 &&
695 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500696 requiresCompositionLayer = true;
697 }
698 for (auto region : layer->blurRegions) {
699 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
700 requiresCompositionLayer = true;
701 }
702 }
703 if (requiresCompositionLayer) {
704 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500705 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500706 blurCompositionLayer = layer;
707 break;
708 }
709 }
710 }
711
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500712 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700713 // Clear the entire canvas with a transparent black to prevent ghost images.
714 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500715 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800716
717 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
718 // view is still on-screen. The clear region could be re-specified as a black color layer,
719 // however.
720 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500721 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800722 size_t numRects = 0;
723 Rect const* rects = display.clearRegion.getArray(&numRects);
724 SkIRect skRects[numRects];
725 for (int i = 0; i < numRects; ++i) {
726 skRects[i] =
727 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
728 }
729 SkRegion clearRegion;
730 SkPaint paint;
731 sk_sp<SkShader> shader =
732 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500733 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800734 paint.setShader(shader);
735 clearRegion.setRects(skRects, numRects);
736 canvas->drawRegion(clearRegion, paint);
737 }
738
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500739 // setup color filter if necessary
740 sk_sp<SkColorFilter> displayColorTransform;
741 if (display.colorTransform != mat4()) {
742 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
743 }
744
John Reck67b1e2b2020-08-26 13:17:24 -0700745 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500746 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100747
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400748 if (kPrintLayerSettings) {
749 std::stringstream ls;
750 PrintTo(*layer, &ls);
751 auto debugs = ls.str();
752 int pos = 0;
753 while (pos < debugs.size()) {
754 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
755 pos += 1000;
756 }
757 }
758
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500759 sk_sp<SkImage> blurInput;
760 if (blurCompositionLayer == layer) {
761 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
762 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
763
764 // save a snapshot of the activeSurface to use as input to the blur shaders
765 blurInput = activeSurface->makeImageSnapshot();
766
767 // TODO we could skip this step if we know the blur will cover the entire image
768 // blit the offscreen framebuffer into the destination AHB
769 SkPaint paint;
770 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500771 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
772 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
773 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
774 String8::format("SurfaceID|%" PRId64, id).c_str(),
775 nullptr);
776 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
777 } else {
778 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
779 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500780
781 // assign dstCanvas to canvas and ensure that the canvas state is up to date
782 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500783 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500784 initCanvas(canvas, display);
785
786 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
787 dstSurface->getCanvas()->getSaveCount());
788 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
789 dstSurface->getCanvas()->getTotalMatrix());
790
791 // assign dstSurface to activeSurface
792 activeSurface = dstSurface;
793 }
794
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500795 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500796 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800797 // Record the name of the layer if the capture is running.
798 std::stringstream layerSettings;
799 PrintTo(*layer, &layerSettings);
800 // Store the LayerSettings in additional information.
801 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
802 SkData::MakeWithCString(layerSettings.str().c_str()));
803 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100804 // Layers have a local transform that should be applied to them
805 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100806
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500807 const auto bounds = getSkRect(layer->geometry.boundaries);
808 if (mBlurFilter && layerHasBlur(layer)) {
809 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
810
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500811 // if multiple layers have blur, then we need to take a snapshot now because
812 // only the lowest layer will have blurImage populated earlier
813 if (!blurInput) {
814 blurInput = activeSurface->makeImageSnapshot();
815 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500816 // rect to be blurred in the coordinate space of blurInput
817 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
818
Lucas Dupinc3800b82020-10-02 16:24:48 -0700819 if (layer->backgroundBlurRadius > 0) {
820 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500821 auto blurredImage =
822 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
823 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100824
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500825 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
826
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500827 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
828 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700829 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500830 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100831 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700832 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500833 cachedBlurs[region.blurRadius] =
834 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
835 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700836 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500837
838 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
839 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700840 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700841 }
842
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500843 // Shadows are assumed to live only on their own layer - it's not valid
844 // to draw the boundary rectangles when there is already a caster shadow
845 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
846 // composition - using a well-defined invalid color is long-term less error-prone.
847 if (layer->shadow.length > 0) {
848 const auto rect = layer->geometry.roundedCornersRadius > 0
849 ? getSkRect(layer->geometry.roundedCornersCrop)
850 : bounds;
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400851 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
852 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500853 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
854 continue;
855 }
856
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500857 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
858 (mUseColorManagement &&
859 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
860
861 // quick abort from drawing the remaining portion of the layer
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400862 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500863 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
864 continue;
865 }
866
867 // If we need to map to linear space or color management is disabled, then mark the source
868 // image with the same colorspace as the destination surface so that Skia's color
869 // management is a no-op.
870 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
871 ? dstDataspace
872 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800873
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500874 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700875 if (layer->source.buffer.buffer) {
876 ATRACE_NAME("DrawImage");
Ady Abraham193426d2021-02-18 14:01:53 -0800877 validateInputBufferUsage(layer->source.buffer.buffer);
John Reck67b1e2b2020-08-26 13:17:24 -0700878 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800879 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400880 auto iter = cache.find(item.buffer->getId());
881 if (iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800882 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700883 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800884 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Derek Sollenberger34257882021-04-06 18:32:34 +0000885 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
886 item.buffer->toAHardwareBuffer(),
887 false));
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400888 cache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700889 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800890
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800891 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500892 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800893 item.usePremultipliedAlpha
894 ? kPremul_SkAlphaType
895 : kUnpremul_SkAlphaType,
896 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700897
898 auto texMatrix = getSkM44(item.textureTransform).asM33();
899 // textureTansform was intended to be passed directly into a shader, so when
900 // building the total matrix with the textureTransform we need to first
901 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500902 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800903 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700904
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800905 SkMatrix matrix;
906 if (!texMatrix.invert(&matrix)) {
907 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700908 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800909 // The shader does not respect the translation, so we add it to the texture
910 // transform for the SkImage. This will make sure that the correct layer contents
911 // are drawn in the correct part of the screen.
912 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700913
Ana Krulecb7b28b22020-11-23 14:48:58 -0800914 sk_sp<SkShader> shader;
915
916 if (layer->source.buffer.useTextureFiltering) {
917 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
918 SkSamplingOptions(
919 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
920 &matrix);
921 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500922 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800923 }
Alec Mouri029d1952020-10-12 10:37:08 -0700924
Alec Mouric0aae732021-01-12 13:32:18 -0800925 // Handle opaque images - it's a little nonstandard how we do this.
926 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
927 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
928 // The important language is that when isOpaque is set, opacity is not sampled from the
929 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
930 // here's the conundrum:
931 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
932 // as an internal hint - composition is undefined when there are alpha bits present.
933 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
934 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
935 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
936 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
937 // of a hack anyways.
938 // 3. We can't change the blendmode to src, because while this satisfies the requirement
939 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
940 // because src always clobbers the destination content.
941 //
942 // So, what we do here instead is an additive blend mode where we compose the input
943 // image with a solid black. This might need to be reassess if this does not support
944 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
945 if (item.isOpaque) {
946 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
947 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500948 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800949 }
950
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500951 paint.setShader(createRuntimeEffectShader(shader, layer, display,
952 !item.isOpaque && item.usePremultipliedAlpha,
953 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800954 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700955 } else {
956 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700957 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800958 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
959 .fG = color.g,
960 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800961 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500962 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800963 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500964 /* undoPremultipliedAlpha */ false,
965 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700966 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700967
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400968 if (layer->disableBlending) {
969 paint.setBlendMode(SkBlendMode::kSrc);
970 }
971
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500972 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700973
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500974 if (layer->geometry.roundedCornersRadius > 0) {
975 paint.setAntiAlias(true);
976 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800977 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500978 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700979 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400980 if (kFlushAfterEveryLayer) {
981 ATRACE_NAME("flush surface");
982 activeSurface->flush();
983 }
John Reck67b1e2b2020-08-26 13:17:24 -0700984 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500985 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800986 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700987 {
988 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500989 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
990 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700991 }
992
993 if (drawFence != nullptr) {
994 *drawFence = flush();
995 }
996
997 // If flush failed or we don't support native fences, we need to force the
998 // gl command stream to be executed.
999 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1000 if (requireSync) {
1001 ATRACE_BEGIN("Submit(sync=true)");
1002 } else {
1003 ATRACE_BEGIN("Submit(sync=false)");
1004 }
Lucas Dupind508e472020-11-04 04:32:06 +00001005 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001006 ATRACE_END();
1007 if (!success) {
1008 ALOGE("Failed to flush RenderEngine commands");
1009 // Chances are, something illegal happened (either the caller passed
1010 // us bad parameters, or we messed up our shader generation).
1011 return INVALID_OPERATION;
1012 }
1013
1014 // checkErrors();
1015 return NO_ERROR;
1016}
1017
Lucas Dupin3f11e922020-09-22 17:31:04 -07001018inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1019 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1020}
1021
1022inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1023 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1024}
1025
Lucas Dupin21f348e2020-09-16 17:31:26 -07001026inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -08001027 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001028 const auto cornerRadius = layer->geometry.roundedCornersRadius;
1029 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
1030}
1031
Galia Peycheva80116e52020-11-06 11:57:25 +01001032inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
1033 const auto rect = getSkRect(layer->geometry.boundaries);
1034 const auto cornersRadius = layer->geometry.roundedCornersRadius;
1035 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
1036 .cornerRadiusTL = cornersRadius,
1037 .cornerRadiusTR = cornersRadius,
1038 .cornerRadiusBL = cornersRadius,
1039 .cornerRadiusBR = cornersRadius,
1040 .alpha = 1,
1041 .left = static_cast<int>(rect.fLeft),
1042 .top = static_cast<int>(rect.fTop),
1043 .right = static_cast<int>(rect.fRight),
1044 .bottom = static_cast<int>(rect.fBottom)};
1045}
1046
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001047inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
1048 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
1049}
1050
Lucas Dupin3f11e922020-09-22 17:31:04 -07001051inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1052 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1053}
1054
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001055inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1056 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1057 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1058 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1059 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1060}
1061
Lucas Dupin3f11e922020-09-22 17:31:04 -07001062inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1063 return SkPoint3::Make(vector.x, vector.y, vector.z);
1064}
1065
John Reck67b1e2b2020-08-26 13:17:24 -07001066size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1067 return mGrContext->maxTextureSize();
1068}
1069
1070size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1071 return mGrContext->maxRenderTargetSize();
1072}
1073
Lucas Dupin3f11e922020-09-22 17:31:04 -07001074void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1075 const ShadowSettings& settings) {
1076 ATRACE_CALL();
1077 const float casterZ = settings.length / 2.0f;
1078 const auto shadowShape = cornerRadius > 0
1079 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1080 : SkPath::Rect(casterRect);
1081 const auto flags =
1082 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1083
1084 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1085 getSkPoint3(settings.lightPos), settings.lightRadius,
1086 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1087 flags);
1088}
1089
John Reck67b1e2b2020-08-26 13:17:24 -07001090EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001091 EGLContext shareContext,
1092 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001093 Protection protection) {
1094 EGLint renderableType = 0;
1095 if (config == EGL_NO_CONFIG_KHR) {
1096 renderableType = EGL_OPENGL_ES3_BIT;
1097 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1098 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1099 }
1100 EGLint contextClientVersion = 0;
1101 if (renderableType & EGL_OPENGL_ES3_BIT) {
1102 contextClientVersion = 3;
1103 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1104 contextClientVersion = 2;
1105 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1106 contextClientVersion = 1;
1107 } else {
1108 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1109 }
1110
1111 std::vector<EGLint> contextAttributes;
1112 contextAttributes.reserve(7);
1113 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1114 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001115 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001116 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001117 switch (*contextPriority) {
1118 case ContextPriority::REALTIME:
1119 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1120 break;
1121 case ContextPriority::MEDIUM:
1122 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1123 break;
1124 case ContextPriority::LOW:
1125 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1126 break;
1127 case ContextPriority::HIGH:
1128 default:
1129 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1130 break;
1131 }
John Reck67b1e2b2020-08-26 13:17:24 -07001132 }
1133 if (protection == Protection::PROTECTED) {
1134 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1135 contextAttributes.push_back(EGL_TRUE);
1136 }
1137 contextAttributes.push_back(EGL_NONE);
1138
1139 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1140
1141 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1142 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1143 // EGL_NO_CONTEXT so that we can abort.
1144 if (config != EGL_NO_CONFIG_KHR) {
1145 return context;
1146 }
1147 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1148 // should try to fall back to GLES 2.
1149 contextAttributes[1] = 2;
1150 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1151 }
1152
1153 return context;
1154}
1155
Alec Mourid6f09462020-12-07 11:18:17 -08001156std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1157 const RenderEngineCreationArgs& args) {
1158 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1159 return std::nullopt;
1160 }
1161
1162 switch (args.contextPriority) {
1163 case RenderEngine::ContextPriority::REALTIME:
1164 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1165 return RenderEngine::ContextPriority::REALTIME;
1166 } else {
1167 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1168 return RenderEngine::ContextPriority::HIGH;
1169 }
1170 case RenderEngine::ContextPriority::HIGH:
1171 case RenderEngine::ContextPriority::MEDIUM:
1172 case RenderEngine::ContextPriority::LOW:
1173 return args.contextPriority;
1174 default:
1175 return std::nullopt;
1176 }
1177}
1178
John Reck67b1e2b2020-08-26 13:17:24 -07001179EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1180 EGLConfig config, int hwcFormat,
1181 Protection protection) {
1182 EGLConfig placeholderConfig = config;
1183 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1184 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1185 }
1186 std::vector<EGLint> attributes;
1187 attributes.reserve(7);
1188 attributes.push_back(EGL_WIDTH);
1189 attributes.push_back(1);
1190 attributes.push_back(EGL_HEIGHT);
1191 attributes.push_back(1);
1192 if (protection == Protection::PROTECTED) {
1193 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1194 attributes.push_back(EGL_TRUE);
1195 }
1196 attributes.push_back(EGL_NONE);
1197
1198 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1199}
1200
Marin Shalamanovcea12ef2021-03-15 17:00:51 +01001201void SkiaGLRenderEngine::cleanFramebufferCache() {
1202 // TODO(b/180767535) Remove this method and use b/180767535 instead, which would allow
1203 // SF to control texture lifecycle more tightly rather than through custom hooks into RE.
1204 std::lock_guard<std::mutex> lock(mRenderingMutex);
1205 mRuntimeEffects.clear();
1206 mProtectedTextureCache.clear();
1207 mTextureCache.clear();
1208}
John Reck67b1e2b2020-08-26 13:17:24 -07001209
Alec Mourid6f09462020-12-07 11:18:17 -08001210int SkiaGLRenderEngine::getContextPriority() {
1211 int value;
1212 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1213 return value;
1214}
1215
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001216void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1217 // This cache multiplier was selected based on review of cache sizes relative
1218 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1219 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1220 // conservative default based on that analysis.
1221 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1222 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1223
1224 // start by resizing the current context
1225 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1226 grContext->setResourceCacheLimit(maxResourceBytes);
1227
1228 // if it is possible to switch contexts then we will resize the other context
1229 if (useProtectedContext(!mInProtectedContext)) {
1230 grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1231 grContext->setResourceCacheLimit(maxResourceBytes);
1232 // reset back to the initial context that was active when this method was called
1233 useProtectedContext(!mInProtectedContext);
1234 }
1235}
1236
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001237void SkiaGLRenderEngine::dump(std::string& result) {
1238 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1239
1240 StringAppendF(&result, "\n ------------RE-----------------\n");
1241 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1242 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1243 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1244 extensions.getVersion());
1245 StringAppendF(&result, "%s\n", extensions.getExtensions());
1246 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1247 supportsProtectedContent());
1248 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001249 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1250 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001251
1252 {
1253 std::lock_guard<std::mutex> lock(mRenderingMutex);
1254 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1255 StringAppendF(&result, "Dumping buffer ids...\n");
1256 // TODO(178539829): It would be nice to know which layer these are coming from and what
1257 // the texture sizes are.
1258 for (const auto& [id, unused] : mTextureCache) {
1259 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1260 }
1261 StringAppendF(&result, "\n");
1262 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1263 mProtectedTextureCache.size());
1264 StringAppendF(&result, "Dumping buffer ids...\n");
1265 for (const auto& [id, unused] : mProtectedTextureCache) {
1266 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1267 }
1268 StringAppendF(&result, "\n");
1269 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1270 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1271 StringAppendF(&result, "- inputDataspace: %s\n",
1272 dataspaceDetails(
1273 static_cast<android_dataspace>(linearEffect.inputDataspace))
1274 .c_str());
1275 StringAppendF(&result, "- outputDataspace: %s\n",
1276 dataspaceDetails(
1277 static_cast<android_dataspace>(linearEffect.outputDataspace))
1278 .c_str());
1279 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1280 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1281 }
1282 }
1283 StringAppendF(&result, "\n");
1284}
1285
John Reck67b1e2b2020-08-26 13:17:24 -07001286} // namespace skia
1287} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001288} // namespace android