blob: 10560bee2276f2ccf61555bb614e321c022daf54 [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"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070059#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080060#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070061
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040062namespace {
63// Debugging settings
64static const bool kPrintLayerSettings = false;
65static const bool kFlushAfterEveryLayer = false;
66} // namespace
67
John Reck67b1e2b2020-08-26 13:17:24 -070068bool checkGlError(const char* op, int lineNumber);
69
70namespace android {
71namespace renderengine {
72namespace skia {
73
Ana Krulec1d12b3b2021-01-27 16:49:51 -080074using base::StringAppendF;
75
John Reck67b1e2b2020-08-26 13:17:24 -070076static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
77 EGLint wanted, EGLConfig* outConfig) {
78 EGLint numConfigs = -1, n = 0;
79 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
80 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
81 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
82 configs.resize(n);
83
84 if (!configs.empty()) {
85 if (attribute != EGL_NONE) {
86 for (EGLConfig config : configs) {
87 EGLint value = 0;
88 eglGetConfigAttrib(dpy, config, attribute, &value);
89 if (wanted == value) {
90 *outConfig = config;
91 return NO_ERROR;
92 }
93 }
94 } else {
95 // just pick the first one
96 *outConfig = configs[0];
97 return NO_ERROR;
98 }
99 }
100
101 return NAME_NOT_FOUND;
102}
103
104static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
105 EGLConfig* config) {
106 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
107 // it is to be used with WIFI displays
108 status_t err;
109 EGLint wantedAttribute;
110 EGLint wantedAttributeValue;
111
112 std::vector<EGLint> attribs;
113 if (renderableType) {
114 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
115 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
116
117 // Default to 8 bits per channel.
118 const EGLint tmpAttribs[] = {
119 EGL_RENDERABLE_TYPE,
120 renderableType,
121 EGL_RECORDABLE_ANDROID,
122 EGL_TRUE,
123 EGL_SURFACE_TYPE,
124 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
125 EGL_FRAMEBUFFER_TARGET_ANDROID,
126 EGL_TRUE,
127 EGL_RED_SIZE,
128 is1010102 ? 10 : 8,
129 EGL_GREEN_SIZE,
130 is1010102 ? 10 : 8,
131 EGL_BLUE_SIZE,
132 is1010102 ? 10 : 8,
133 EGL_ALPHA_SIZE,
134 is1010102 ? 2 : 8,
135 EGL_NONE,
136 };
137 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
138 std::back_inserter(attribs));
139 wantedAttribute = EGL_NONE;
140 wantedAttributeValue = EGL_NONE;
141 } else {
142 // if no renderable type specified, fallback to a simplified query
143 wantedAttribute = EGL_NATIVE_VISUAL_ID;
144 wantedAttributeValue = format;
145 }
146
147 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
148 config);
149 if (err == NO_ERROR) {
150 EGLint caveat;
151 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
152 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
153 }
154
155 return err;
156}
157
158std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
159 const RenderEngineCreationArgs& args) {
160 // initialize EGL for the default display
161 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
162 if (!eglInitialize(display, nullptr, nullptr)) {
163 LOG_ALWAYS_FATAL("failed to initialize EGL");
164 }
165
Yiwei Zhange2650962020-12-01 23:27:58 +0000166 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700167 if (!eglVersion) {
168 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000169 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700170 }
171
Yiwei Zhange2650962020-12-01 23:27:58 +0000172 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700173 if (!eglExtensions) {
174 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000175 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700176 }
177
178 auto& extensions = gl::GLExtensions::getInstance();
179 extensions.initWithEGLStrings(eglVersion, eglExtensions);
180
181 // The code assumes that ES2 or later is available if this extension is
182 // supported.
183 EGLConfig config = EGL_NO_CONFIG_KHR;
184 if (!extensions.hasNoConfigContext()) {
185 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
186 }
187
John Reck67b1e2b2020-08-26 13:17:24 -0700188 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800189 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700190 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800191 protectedContext =
192 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700193 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
194 }
195
Alec Mourid6f09462020-12-07 11:18:17 -0800196 EGLContext ctxt =
197 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700198
199 // if can't create a GL context, we can only abort.
200 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
201
202 EGLSurface placeholder = EGL_NO_SURFACE;
203 if (!extensions.hasSurfacelessContext()) {
204 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
205 Protection::UNPROTECTED);
206 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
207 }
208 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
209 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
210 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
211 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
212
213 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
214 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
215 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
216 Protection::PROTECTED);
217 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
218 "can't create protected placeholder pbuffer");
219 }
220
221 // initialize the renderer while GL is current
222 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000223 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
224 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700225
226 ALOGI("OpenGL ES informations:");
227 ALOGI("vendor : %s", extensions.getVendor());
228 ALOGI("renderer : %s", extensions.getRenderer());
229 ALOGI("version : %s", extensions.getVersion());
230 ALOGI("extensions: %s", extensions.getExtensions());
231 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
232 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
233
234 return engine;
235}
236
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500237void SkiaGLRenderEngine::primeCache() {
238 Cache::primeShaderCache(this);
239}
240
John Reck67b1e2b2020-08-26 13:17:24 -0700241EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
242 status_t err;
243 EGLConfig config;
244
245 // First try to get an ES3 config
246 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
247 if (err != NO_ERROR) {
248 // If ES3 fails, try to get an ES2 config
249 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
250 if (err != NO_ERROR) {
251 // If ES2 still doesn't work, probably because we're on the emulator.
252 // try a simplified query
253 ALOGW("no suitable EGLConfig found, trying a simpler query");
254 err = selectEGLConfig(display, format, 0, &config);
255 if (err != NO_ERROR) {
256 // this EGL is too lame for android
257 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
258 }
259 }
260 }
261
262 if (logConfig) {
263 // print some debugging info
264 EGLint r, g, b, a;
265 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
266 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
267 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
268 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
269 ALOGI("EGL information:");
270 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
271 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
272 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
273 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
274 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
275 }
276
277 return config;
278}
279
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400280sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
281 // This "cache" does not actually cache anything. It just allows us to
282 // monitor Skia's internal cache. So this method always returns null.
283 return nullptr;
284}
285
286void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
287 const SkString& description) {
288 mShadersCachedSinceLastCall++;
289}
290
291void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
292 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
293 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
294 numShaders, cached);
295}
296
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400297int SkiaGLRenderEngine::reportShadersCompiled() {
298 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
299}
300
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700301SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000302 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700303 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800304 : SkiaRenderEngine(args.renderEngineType),
305 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700306 mEGLContext(ctxt),
307 mPlaceholderSurface(placeholder),
308 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700309 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400310 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800311 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700312 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
313 LOG_ALWAYS_FATAL_IF(!glInterface.get());
314
315 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400316 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700317 options.fDisableDistanceFieldPaths = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400318 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000319 mGrContext = GrDirectContext::MakeGL(glInterface, options);
320 if (useProtectedContext(true)) {
321 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
322 useProtectedContext(false);
323 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700324
325 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500326 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700327 mBlurFilter = new BlurFilter();
328 }
Alec Mouric0aae732021-01-12 13:32:18 -0800329 mCapture = std::make_unique<SkiaCapture>();
330}
331
332SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100333 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800334 if (mBlurFilter) {
335 delete mBlurFilter;
336 }
337
338 mCapture = nullptr;
339
340 mGrContext->flushAndSubmit(true);
341 mGrContext->abandonContext();
342
343 if (mProtectedGrContext) {
344 mProtectedGrContext->flushAndSubmit(true);
345 mProtectedGrContext->abandonContext();
346 }
347
348 if (mPlaceholderSurface != EGL_NO_SURFACE) {
349 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
350 }
351 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
352 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
353 }
354 if (mEGLContext != EGL_NO_CONTEXT) {
355 eglDestroyContext(mEGLDisplay, mEGLContext);
356 }
357 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
358 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
359 }
360 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
361 eglTerminate(mEGLDisplay);
362 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700363}
364
Lucas Dupind508e472020-11-04 04:32:06 +0000365bool SkiaGLRenderEngine::supportsProtectedContent() const {
366 return mProtectedEGLContext != EGL_NO_CONTEXT;
367}
368
369bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
370 if (useProtectedContext == mInProtectedContext) {
371 return true;
372 }
Alec Mourif6a07812021-02-11 21:07:55 -0800373 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000374 return false;
375 }
376 const EGLSurface surface =
377 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
378 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
379 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800380
Lucas Dupind508e472020-11-04 04:32:06 +0000381 if (success) {
382 mInProtectedContext = useProtectedContext;
383 }
384 return success;
385}
386
John Reck67b1e2b2020-08-26 13:17:24 -0700387base::unique_fd SkiaGLRenderEngine::flush() {
388 ATRACE_CALL();
389 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
390 return base::unique_fd();
391 }
392
393 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
394 if (sync == EGL_NO_SYNC_KHR) {
395 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
396 return base::unique_fd();
397 }
398
399 // native fence fd will not be populated until flush() is done.
400 glFlush();
401
402 // get the fence fd
403 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
404 eglDestroySyncKHR(mEGLDisplay, sync);
405 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
406 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
407 }
408
409 return fenceFd;
410}
411
412bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
413 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
414 !gl::GLExtensions::getInstance().hasWaitSync()) {
415 return false;
416 }
417
418 // release the fd and transfer the ownership to EGLSync
419 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
420 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
421 if (sync == EGL_NO_SYNC_KHR) {
422 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
423 return false;
424 }
425
426 // XXX: The spec draft is inconsistent as to whether this should return an
427 // EGLint or void. Ignore the return value for now, as it's not strictly
428 // needed.
429 eglWaitSyncKHR(mEGLDisplay, sync, 0);
430 EGLint error = eglGetError();
431 eglDestroySyncKHR(mEGLDisplay, sync);
432 if (error != EGL_SUCCESS) {
433 ALOGE("failed to wait for EGL native fence sync: %#x", error);
434 return false;
435 }
436
437 return true;
438}
439
Alec Mouri678245d2020-09-30 16:58:23 -0700440static float toDegrees(uint32_t transform) {
441 switch (transform) {
442 case ui::Transform::ROT_90:
443 return 90.0;
444 case ui::Transform::ROT_180:
445 return 180.0;
446 case ui::Transform::ROT_270:
447 return 270.0;
448 default:
449 return 0.0;
450 }
451}
452
Alec Mourib34f0b72020-10-02 13:18:34 -0700453static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
454 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
455 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
456 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
457 matrix[3][3], 0);
458}
459
Alec Mouri029d1952020-10-12 10:37:08 -0700460static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
461 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
462 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
463
464 // Treat unsupported dataspaces as srgb
465 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
466 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
467 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
468 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
469 }
470
471 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
472 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
473 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
474 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
475 }
476
477 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
478 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
479 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
480 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
481
482 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
483 sourceTransfer != destTransfer;
484}
485
Alec Mouria90a5702021-04-16 16:36:21 +0000486void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
487 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800488 // Only run this if RE is running on its own thread. This way the access to GL
489 // operations is guaranteed to be happening on the same thread.
490 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
491 return;
492 }
493 ATRACE_CALL();
494
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400495 // We need to switch the currently bound context if the buffer is protected but the current
496 // context is not. The current state must then be restored after the buffer is cached.
497 const bool protectedContextState = mInProtectedContext;
498 if (!useProtectedContext(protectedContextState ||
499 (buffer->getUsage() & GRALLOC_USAGE_PROTECTED))) {
500 ALOGE("Attempting to cache a buffer into a different context than what is currently bound");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800501 return;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400502 }
503
504 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
505 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
506
507 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000508 mGraphicBufferExternalRefs[buffer->getId()]++;
509
510 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800511 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400512 std::make_shared<AutoBackendTexture::LocalRef>(grContext.get(),
513 buffer->toAHardwareBuffer(),
514 isRenderable);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400515 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800516 }
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400517 // restore the original state of the protected context if necessary
518 useProtectedContext(protectedContextState);
Ana Krulecdfec8f52021-01-13 12:51:47 -0800519}
520
Alec Mouria90a5702021-04-16 16:36:21 +0000521void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800522 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700523 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000524 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
525 iter != mGraphicBufferExternalRefs.end()) {
526 if (iter->second == 0) {
527 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
528 "> from RenderEngine texture, but the "
529 "ref count was already zero!",
530 buffer->getId());
531 mGraphicBufferExternalRefs.erase(buffer->getId());
532 return;
533 }
534
535 iter->second--;
536
537 if (iter->second == 0) {
538 mTextureCache.erase(buffer->getId());
539 mProtectedTextureCache.erase(buffer->getId());
540 mGraphicBufferExternalRefs.erase(buffer->getId());
541 }
542 }
John Reck67b1e2b2020-08-26 13:17:24 -0700543}
544
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700545sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
546 sk_sp<SkShader> shader,
547 const LayerSettings* layer, const DisplaySettings& display, bool undoPremultipliedAlpha,
548 bool requiresLinearEffect) {
549 const auto stretchEffect = layer->stretchEffect;
550 if (stretchEffect.hasEffect()) {
551 const auto targetBuffer = layer->source.buffer.buffer;
552 const auto graphicsBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
553 if (graphicsBuffer && shader) {
554 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
555 }
John Reckcdb4ed72021-02-04 13:39:33 -0500556 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700557
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500558 if (requiresLinearEffect) {
559 const ui::Dataspace inputDataspace =
560 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
561 const ui::Dataspace outputDataspace =
562 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
563
564 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
565 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800566 .undoPremultipliedAlpha = undoPremultipliedAlpha};
567
568 auto effectIter = mRuntimeEffects.find(effect);
569 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
570 if (effectIter == mRuntimeEffects.end()) {
571 runtimeEffect = buildRuntimeEffect(effect);
572 mRuntimeEffects.insert({effect, runtimeEffect});
573 } else {
574 runtimeEffect = effectIter->second;
575 }
576 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
577 display.maxLuminance,
578 layer->source.buffer.maxMasteringLuminance,
579 layer->source.buffer.maxContentLuminance);
580 }
581 return shader;
582}
583
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500584void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500585 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500586 // Record display settings when capture is running.
587 std::stringstream displaySettings;
588 PrintTo(display, &displaySettings);
589 // Store the DisplaySettings in additional information.
590 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
591 SkData::MakeWithCString(displaySettings.str().c_str()));
592 }
593
594 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
595 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
596 // displays might have different scaling when compared to the physical screen.
597
598 canvas->clipRect(getSkRect(display.physicalDisplay));
599 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
600
601 const auto clipWidth = display.clip.width();
602 const auto clipHeight = display.clip.height();
603 auto rotatedClipWidth = clipWidth;
604 auto rotatedClipHeight = clipHeight;
605 // Scale is contingent on the rotation result.
606 if (display.orientation & ui::Transform::ROT_90) {
607 std::swap(rotatedClipWidth, rotatedClipHeight);
608 }
609 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
610 static_cast<SkScalar>(rotatedClipWidth);
611 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
612 static_cast<SkScalar>(rotatedClipHeight);
613 canvas->scale(scaleX, scaleY);
614
615 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
616 // back so that the top left corner of the clip is at (0, 0).
617 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
618 canvas->rotate(toDegrees(display.orientation));
619 canvas->translate(-clipWidth / 2, -clipHeight / 2);
620 canvas->translate(-display.clip.left, -display.clip.top);
621}
622
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500623class AutoSaveRestore {
624public:
625 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
626 ~AutoSaveRestore() { restore(); }
627 void replace(SkCanvas* canvas) {
628 mCanvas = canvas;
629 mSaveCount = canvas->save();
630 }
631 void restore() {
632 if (mCanvas) {
633 mCanvas->restoreToCount(mSaveCount);
634 mCanvas = nullptr;
635 }
636 }
637
638private:
639 SkCanvas* mCanvas;
640 int mSaveCount;
641};
642
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700643void drawStretch(const SkRect& bounds, const StretchEffect& stretchEffect,
644 SkCanvas* canvas, const SkPaint& paint) {
645 float top = bounds.top();
646 float left = bounds.left();
647 float bottom = bounds.bottom();
648 float right = bounds.right();
649 // Adjust the drawing bounds based on the stretch itself.
650 float stretchOffsetX =
651 round(bounds.width() * stretchEffect.getStretchWidthMultiplier());
652 float stretchOffsetY =
653 round(bounds.height() * stretchEffect.getStretchHeightMultiplier());
654 if (stretchEffect.vectorY < 0.f) {
655 top -= stretchOffsetY;
656 } else if (stretchEffect.vectorY > 0.f){
657 bottom += stretchOffsetY;
658 }
659
660 if (stretchEffect.vectorX < 0.f) {
661 left -= stretchOffsetX;
662 } else if (stretchEffect.vectorX > 0.f) {
663 right += stretchOffsetX;
664 }
665
666 auto stretchBounds = SkRect::MakeLTRB(left, top, right, bottom);
667 canvas->drawRect(stretchBounds, paint);
668}
669
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400670static SkRRect getBlurRRect(const BlurRegion& region) {
671 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
672 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
673 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
674 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
675 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
676 SkRRect roundedRect;
677 roundedRect.setRectRadii(rect, radii);
678 return roundedRect;
679}
680
John Reck67b1e2b2020-08-26 13:17:24 -0700681status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
682 const std::vector<const LayerSettings*>& layers,
Alec Mouria90a5702021-04-16 16:36:21 +0000683 const std::shared_ptr<ExternalTexture>& buffer,
684 const bool /*useFramebufferCache*/,
John Reck67b1e2b2020-08-26 13:17:24 -0700685 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
686 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800687
John Reck67b1e2b2020-08-26 13:17:24 -0700688 std::lock_guard<std::mutex> lock(mRenderingMutex);
689 if (layers.empty()) {
690 ALOGV("Drawing empty layer stack");
691 return NO_ERROR;
692 }
693
694 if (bufferFence.get() >= 0) {
695 // Duplicate the fence for passing to waitFence.
696 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
697 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
698 ATRACE_NAME("Waiting before draw");
699 sync_wait(bufferFence.get(), -1);
700 }
701 }
702 if (buffer == nullptr) {
703 ALOGE("No output buffer provided. Aborting GPU composition.");
704 return BAD_VALUE;
705 }
706
Alec Mouria90a5702021-04-16 16:36:21 +0000707 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800708
Lucas Dupind508e472020-11-04 04:32:06 +0000709 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800710 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700711
Alec Mouria90a5702021-04-16 16:36:21 +0000712 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
713 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
714 surfaceTextureRef = it->second;
715 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400716 surfaceTextureRef =
717 std::make_shared<AutoBackendTexture::LocalRef>(grContext.get(),
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700718 buffer->getBuffer()->toAHardwareBuffer(), true);
John Reck67b1e2b2020-08-26 13:17:24 -0700719 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800720
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500721 const ui::Dataspace dstDataspace =
722 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500723 sk_sp<SkSurface> dstSurface =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400724 surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700725
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500726 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
727 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800728 ALOGE("Cannot acquire canvas from Skia.");
729 return BAD_VALUE;
730 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500731
732 // Find if any layers have requested blur, we'll use that info to decide when to render to an
733 // offscreen buffer and when to render to the native buffer.
734 sk_sp<SkSurface> activeSurface(dstSurface);
735 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500736 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500737 const LayerSettings* blurCompositionLayer = nullptr;
738 if (mBlurFilter) {
739 bool requiresCompositionLayer = false;
740 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500741 if (layer->backgroundBlurRadius > 0 &&
742 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500743 requiresCompositionLayer = true;
744 }
745 for (auto region : layer->blurRegions) {
746 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
747 requiresCompositionLayer = true;
748 }
749 }
750 if (requiresCompositionLayer) {
751 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500752 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500753 blurCompositionLayer = layer;
754 break;
755 }
756 }
757 }
758
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500759 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700760 // Clear the entire canvas with a transparent black to prevent ghost images.
761 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500762 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800763
764 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
765 // view is still on-screen. The clear region could be re-specified as a black color layer,
766 // however.
767 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500768 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800769 size_t numRects = 0;
770 Rect const* rects = display.clearRegion.getArray(&numRects);
771 SkIRect skRects[numRects];
772 for (int i = 0; i < numRects; ++i) {
773 skRects[i] =
774 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
775 }
776 SkRegion clearRegion;
777 SkPaint paint;
778 sk_sp<SkShader> shader =
779 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500780 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800781 paint.setShader(shader);
782 clearRegion.setRects(skRects, numRects);
783 canvas->drawRegion(clearRegion, paint);
784 }
785
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500786 // setup color filter if necessary
787 sk_sp<SkColorFilter> displayColorTransform;
788 if (display.colorTransform != mat4()) {
789 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
790 }
791
John Reck67b1e2b2020-08-26 13:17:24 -0700792 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500793 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100794
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400795 if (kPrintLayerSettings) {
796 std::stringstream ls;
797 PrintTo(*layer, &ls);
798 auto debugs = ls.str();
799 int pos = 0;
800 while (pos < debugs.size()) {
801 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
802 pos += 1000;
803 }
804 }
805
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500806 sk_sp<SkImage> blurInput;
807 if (blurCompositionLayer == layer) {
808 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
809 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
810
811 // save a snapshot of the activeSurface to use as input to the blur shaders
812 blurInput = activeSurface->makeImageSnapshot();
813
814 // TODO we could skip this step if we know the blur will cover the entire image
815 // blit the offscreen framebuffer into the destination AHB
816 SkPaint paint;
817 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500818 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
819 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
820 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
821 String8::format("SurfaceID|%" PRId64, id).c_str(),
822 nullptr);
823 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
824 } else {
825 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
826 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500827
828 // assign dstCanvas to canvas and ensure that the canvas state is up to date
829 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500830 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500831 initCanvas(canvas, display);
832
833 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
834 dstSurface->getCanvas()->getSaveCount());
835 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
836 dstSurface->getCanvas()->getTotalMatrix());
837
838 // assign dstSurface to activeSurface
839 activeSurface = dstSurface;
840 }
841
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500842 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500843 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800844 // Record the name of the layer if the capture is running.
845 std::stringstream layerSettings;
846 PrintTo(*layer, &layerSettings);
847 // Store the LayerSettings in additional information.
848 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
849 SkData::MakeWithCString(layerSettings.str().c_str()));
850 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100851 // Layers have a local transform that should be applied to them
852 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100853
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400854 const auto [bounds, roundRectClip] = getBoundsAndClip(layer);
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500855 if (mBlurFilter && layerHasBlur(layer)) {
856 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
857
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500858 // if multiple layers have blur, then we need to take a snapshot now because
859 // only the lowest layer will have blurImage populated earlier
860 if (!blurInput) {
861 blurInput = activeSurface->makeImageSnapshot();
862 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500863 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400864 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
865
866 // if the clip needs to be applied then apply it now and make sure
867 // it is restored before we attempt to draw any shadows.
868 SkAutoCanvasRestore acr(canvas, true);
869 if (!roundRectClip.isEmpty()) {
870 canvas->clipRRect(roundRectClip, true);
871 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500872
Galia Peychevae425ac82021-03-15 17:12:03 +0100873 // TODO(b/182216890): Filter out empty layers earlier
874 if (blurRect.width() > 0 && blurRect.height() > 0) {
875 if (layer->backgroundBlurRadius > 0) {
876 ATRACE_NAME("BackgroundBlur");
877 auto blurredImage =
878 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
879 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100880
Galia Peychevae425ac82021-03-15 17:12:03 +0100881 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500882
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400883 mBlurFilter->drawBlurRegion(canvas, bounds, layer->backgroundBlurRadius, 1.0f,
884 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700885 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400886
Derek Sollenberger39feade2021-04-27 16:08:40 -0400887 canvas->concat(getSkM44(layer->blurRegionTransform).asM33());
Galia Peychevae425ac82021-03-15 17:12:03 +0100888 for (auto region : layer->blurRegions) {
889 if (cachedBlurs[region.blurRadius] == nullptr) {
890 ATRACE_NAME("BlurRegion");
891 cachedBlurs[region.blurRadius] =
892 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
893 blurRect);
894 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500895
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400896 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
897 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100898 cachedBlurs[region.blurRadius], blurInput);
899 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700900 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700901 }
902
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500903 // Shadows are assumed to live only on their own layer - it's not valid
904 // to draw the boundary rectangles when there is already a caster shadow
905 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
906 // composition - using a well-defined invalid color is long-term less error-prone.
907 if (layer->shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400908 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
909 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -0400910 drawShadow(canvas, bounds, layer->shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500911 continue;
912 }
913
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500914 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
915 (mUseColorManagement &&
916 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
917
918 // quick abort from drawing the remaining portion of the layer
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400919 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500920 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
921 continue;
922 }
923
924 // If we need to map to linear space or color management is disabled, then mark the source
925 // image with the same colorspace as the destination surface so that Skia's color
926 // management is a no-op.
927 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
928 ? dstDataspace
929 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800930
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500931 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700932 if (layer->source.buffer.buffer) {
933 ATRACE_NAME("DrawImage");
Alec Mouria90a5702021-04-16 16:36:21 +0000934 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700935 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800936 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000937
938 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
939 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800940 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700941 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000942 // If we didn't find the image in the cache, then create a local ref but don't cache
943 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
944 // we didn't find anything in the cache then we intentionally did not cache this
945 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400946 imageTextureRef = std::make_shared<
947 AutoBackendTexture::LocalRef>(grContext.get(),
948 item.buffer->getBuffer()->toAHardwareBuffer(),
949 false);
John Reck67b1e2b2020-08-26 13:17:24 -0700950 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800951
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800952 sk_sp<SkImage> image =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400953 imageTextureRef->makeImage(layerDataspace,
954 item.usePremultipliedAlpha ? kPremul_SkAlphaType
955 : kUnpremul_SkAlphaType,
956 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700957
958 auto texMatrix = getSkM44(item.textureTransform).asM33();
959 // textureTansform was intended to be passed directly into a shader, so when
960 // building the total matrix with the textureTransform we need to first
961 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500962 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800963 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700964
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800965 SkMatrix matrix;
966 if (!texMatrix.invert(&matrix)) {
967 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700968 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800969 // The shader does not respect the translation, so we add it to the texture
970 // transform for the SkImage. This will make sure that the correct layer contents
971 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400972 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -0700973
Ana Krulecb7b28b22020-11-23 14:48:58 -0800974 sk_sp<SkShader> shader;
975
976 if (layer->source.buffer.useTextureFiltering) {
977 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
978 SkSamplingOptions(
979 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
980 &matrix);
981 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500982 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800983 }
Alec Mouri029d1952020-10-12 10:37:08 -0700984
Alec Mouric0aae732021-01-12 13:32:18 -0800985 // Handle opaque images - it's a little nonstandard how we do this.
986 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
987 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
988 // The important language is that when isOpaque is set, opacity is not sampled from the
989 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
990 // here's the conundrum:
991 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
992 // as an internal hint - composition is undefined when there are alpha bits present.
993 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
994 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
995 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
996 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
997 // of a hack anyways.
998 // 3. We can't change the blendmode to src, because while this satisfies the requirement
999 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
1000 // because src always clobbers the destination content.
1001 //
1002 // So, what we do here instead is an additive blend mode where we compose the input
1003 // image with a solid black. This might need to be reassess if this does not support
1004 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
1005 if (item.isOpaque) {
1006 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1007 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001008 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001009 }
1010
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001011 paint.setShader(createRuntimeEffectShader(shader, layer, display,
1012 !item.isOpaque && item.usePremultipliedAlpha,
1013 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -08001014 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -07001015 } else {
1016 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -07001017 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001018 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1019 .fG = color.g,
1020 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -08001021 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001022 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -08001023 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001024 /* undoPremultipliedAlpha */ false,
1025 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -07001026 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001027
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001028 if (layer->disableBlending) {
1029 paint.setBlendMode(SkBlendMode::kSrc);
1030 }
1031
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001032 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -07001033
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001034 if (!roundRectClip.isEmpty()) {
1035 canvas->clipRRect(roundRectClip, true);
1036 }
1037
1038 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001039 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001040 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001041 } else {
Nader Jawad2dfc98b2021-04-08 20:35:39 -07001042 auto& stretchEffect = layer->stretchEffect;
1043 // TODO (njawad) temporarily disable manipulation of geometry
1044 // the layer bounds will be updated in HWUI instead of RenderEngine
1045 // in a subsequent CL
1046 // Keep the method call in a dead code path to make -Werror happy
1047 // with unused methods
1048 if (stretchEffect.hasEffect() && /* DISABLES CODE */ (false)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001049 drawStretch(bounds.rect(), stretchEffect, canvas, paint);
Nader Jawad2dfc98b2021-04-08 20:35:39 -07001050 } else {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001051 canvas->drawRect(bounds.rect(), paint);
Nader Jawad2dfc98b2021-04-08 20:35:39 -07001052 }
Lucas Dupin3f11e922020-09-22 17:31:04 -07001053 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001054 if (kFlushAfterEveryLayer) {
1055 ATRACE_NAME("flush surface");
1056 activeSurface->flush();
1057 }
John Reck67b1e2b2020-08-26 13:17:24 -07001058 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001059 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001060 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001061 {
1062 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001063 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1064 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001065 }
1066
1067 if (drawFence != nullptr) {
1068 *drawFence = flush();
1069 }
1070
1071 // If flush failed or we don't support native fences, we need to force the
1072 // gl command stream to be executed.
1073 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1074 if (requireSync) {
1075 ATRACE_BEGIN("Submit(sync=true)");
1076 } else {
1077 ATRACE_BEGIN("Submit(sync=false)");
1078 }
Lucas Dupind508e472020-11-04 04:32:06 +00001079 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001080 ATRACE_END();
1081 if (!success) {
1082 ALOGE("Failed to flush RenderEngine commands");
1083 // Chances are, something illegal happened (either the caller passed
1084 // us bad parameters, or we messed up our shader generation).
1085 return INVALID_OPERATION;
1086 }
1087
1088 // checkErrors();
1089 return NO_ERROR;
1090}
1091
Lucas Dupin3f11e922020-09-22 17:31:04 -07001092inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1093 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1094}
1095
1096inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1097 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1098}
1099
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001100inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(
1101 const LayerSettings* layer) {
1102 const auto bounds = getSkRect(layer->geometry.boundaries);
1103 const auto crop = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001104 const auto cornerRadius = layer->geometry.roundedCornersRadius;
Lucas Dupin21f348e2020-09-16 17:31:26 -07001105
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001106 SkRRect clip;
1107 if (cornerRadius > 0) {
1108 // it the crop and the bounds are equivalent then we don't need a clip
1109 if (bounds == crop) {
1110 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1111 }
1112
1113 // This makes an effort to speed up common, simple bounds + clip combinations by
1114 // converting them to a single RRect draw. It is possible there are other cases
1115 // that can be converted.
1116 if (crop.contains(bounds)) {
1117 bool intersectionIsRoundRect = true;
1118 // check each cropped corner to ensure that it exactly matches the crop or is full
1119 SkVector radii[4];
1120
1121 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
1122
1123 // compute the UpperLeft corner radius
1124 if (bounds.fLeft == crop.fLeft && bounds.fTop == crop.fTop) {
1125 radii[0].set(cornerRadius, cornerRadius);
1126 } else if (bounds.fLeft > insetCrop.fLeft && bounds.fTop > insetCrop.fTop) {
1127 radii[0].set(0, 0);
1128 } else {
1129 intersectionIsRoundRect = false;
1130 }
1131 // compute the UpperRight corner radius
1132 if (bounds.fRight == crop.fRight && bounds.fTop == crop.fTop) {
1133 radii[1].set(cornerRadius, cornerRadius);
1134 } else if (bounds.fRight < insetCrop.fRight && bounds.fTop > insetCrop.fTop) {
1135 radii[1].set(0, 0);
1136 } else {
1137 intersectionIsRoundRect = false;
1138 }
1139 // compute the BottomRight corner radius
1140 if (bounds.fRight == crop.fRight && bounds.fBottom == crop.fBottom) {
1141 radii[2].set(cornerRadius, cornerRadius);
1142 } else if (bounds.fRight < insetCrop.fRight && bounds.fBottom < insetCrop.fBottom) {
1143 radii[2].set(0, 0);
1144 } else {
1145 intersectionIsRoundRect = false;
1146 }
1147 // compute the BottomLeft corner radius
1148 if (bounds.fLeft == crop.fLeft && bounds.fBottom == crop.fBottom) {
1149 radii[3].set(cornerRadius, cornerRadius);
1150 } else if (bounds.fLeft > insetCrop.fLeft && bounds.fBottom < insetCrop.fBottom) {
1151 radii[3].set(0, 0);
1152 } else {
1153 intersectionIsRoundRect = false;
1154 }
1155
1156 if (intersectionIsRoundRect) {
1157 SkRRect intersectionBounds;
1158 intersectionBounds.setRectRadii(bounds, radii);
1159 return {intersectionBounds, clip};
1160 }
1161 }
1162
1163 // we didn't it any of our fast paths so set the clip to the cropRect
1164 clip.setRectXY(crop, cornerRadius, cornerRadius);
1165 }
1166
1167 // if we hit this point then we either don't have rounded corners or we are going to rely
1168 // on the clip to round the corners for us
1169 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001170}
1171
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001172inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
1173 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
1174}
1175
Lucas Dupin3f11e922020-09-22 17:31:04 -07001176inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1177 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1178}
1179
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001180inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1181 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1182 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1183 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1184 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1185}
1186
Lucas Dupin3f11e922020-09-22 17:31:04 -07001187inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1188 return SkPoint3::Make(vector.x, vector.y, vector.z);
1189}
1190
John Reck67b1e2b2020-08-26 13:17:24 -07001191size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1192 return mGrContext->maxTextureSize();
1193}
1194
1195size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1196 return mGrContext->maxRenderTargetSize();
1197}
1198
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001199void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001200 const ShadowSettings& settings) {
1201 ATRACE_CALL();
1202 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001203 const auto flags =
1204 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1205
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001206 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001207 getSkPoint3(settings.lightPos), settings.lightRadius,
1208 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1209 flags);
1210}
1211
John Reck67b1e2b2020-08-26 13:17:24 -07001212EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001213 EGLContext shareContext,
1214 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001215 Protection protection) {
1216 EGLint renderableType = 0;
1217 if (config == EGL_NO_CONFIG_KHR) {
1218 renderableType = EGL_OPENGL_ES3_BIT;
1219 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1220 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1221 }
1222 EGLint contextClientVersion = 0;
1223 if (renderableType & EGL_OPENGL_ES3_BIT) {
1224 contextClientVersion = 3;
1225 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1226 contextClientVersion = 2;
1227 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1228 contextClientVersion = 1;
1229 } else {
1230 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1231 }
1232
1233 std::vector<EGLint> contextAttributes;
1234 contextAttributes.reserve(7);
1235 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1236 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001237 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001238 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001239 switch (*contextPriority) {
1240 case ContextPriority::REALTIME:
1241 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1242 break;
1243 case ContextPriority::MEDIUM:
1244 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1245 break;
1246 case ContextPriority::LOW:
1247 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1248 break;
1249 case ContextPriority::HIGH:
1250 default:
1251 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1252 break;
1253 }
John Reck67b1e2b2020-08-26 13:17:24 -07001254 }
1255 if (protection == Protection::PROTECTED) {
1256 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1257 contextAttributes.push_back(EGL_TRUE);
1258 }
1259 contextAttributes.push_back(EGL_NONE);
1260
1261 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1262
1263 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1264 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1265 // EGL_NO_CONTEXT so that we can abort.
1266 if (config != EGL_NO_CONFIG_KHR) {
1267 return context;
1268 }
1269 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1270 // should try to fall back to GLES 2.
1271 contextAttributes[1] = 2;
1272 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1273 }
1274
1275 return context;
1276}
1277
Alec Mourid6f09462020-12-07 11:18:17 -08001278std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1279 const RenderEngineCreationArgs& args) {
1280 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1281 return std::nullopt;
1282 }
1283
1284 switch (args.contextPriority) {
1285 case RenderEngine::ContextPriority::REALTIME:
1286 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1287 return RenderEngine::ContextPriority::REALTIME;
1288 } else {
1289 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1290 return RenderEngine::ContextPriority::HIGH;
1291 }
1292 case RenderEngine::ContextPriority::HIGH:
1293 case RenderEngine::ContextPriority::MEDIUM:
1294 case RenderEngine::ContextPriority::LOW:
1295 return args.contextPriority;
1296 default:
1297 return std::nullopt;
1298 }
1299}
1300
John Reck67b1e2b2020-08-26 13:17:24 -07001301EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1302 EGLConfig config, int hwcFormat,
1303 Protection protection) {
1304 EGLConfig placeholderConfig = config;
1305 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1306 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1307 }
1308 std::vector<EGLint> attributes;
1309 attributes.reserve(7);
1310 attributes.push_back(EGL_WIDTH);
1311 attributes.push_back(1);
1312 attributes.push_back(EGL_HEIGHT);
1313 attributes.push_back(1);
1314 if (protection == Protection::PROTECTED) {
1315 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1316 attributes.push_back(EGL_TRUE);
1317 }
1318 attributes.push_back(EGL_NONE);
1319
1320 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1321}
1322
Alec Mourid6f09462020-12-07 11:18:17 -08001323int SkiaGLRenderEngine::getContextPriority() {
1324 int value;
1325 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1326 return value;
1327}
1328
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001329void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1330 // This cache multiplier was selected based on review of cache sizes relative
1331 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1332 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1333 // conservative default based on that analysis.
1334 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1335 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1336
1337 // start by resizing the current context
1338 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1339 grContext->setResourceCacheLimit(maxResourceBytes);
1340
1341 // if it is possible to switch contexts then we will resize the other context
1342 if (useProtectedContext(!mInProtectedContext)) {
1343 grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1344 grContext->setResourceCacheLimit(maxResourceBytes);
1345 // reset back to the initial context that was active when this method was called
1346 useProtectedContext(!mInProtectedContext);
1347 }
1348}
1349
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001350void SkiaGLRenderEngine::dump(std::string& result) {
1351 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1352
1353 StringAppendF(&result, "\n ------------RE-----------------\n");
1354 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1355 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1356 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1357 extensions.getVersion());
1358 StringAppendF(&result, "%s\n", extensions.getExtensions());
1359 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1360 supportsProtectedContent());
1361 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001362 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1363 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001364
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001365 std::vector<ResourcePair> cpuResourceMap = {
1366 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1367 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1368 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1369 {"skia/sk_resource_cache/tessellated", "Shadows"},
1370 {"skia", "Other"},
1371 };
1372 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1373 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1374 StringAppendF(&result, "Skia CPU Caches: ");
1375 cpuReporter.logTotals(result);
1376 cpuReporter.logOutput(result);
1377
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001378 {
1379 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001380
1381 std::vector<ResourcePair> gpuResourceMap = {
1382 {"texture_renderbuffer", "Texture/RenderBuffer"},
1383 {"texture", "Texture"},
1384 {"gr_text_blob_cache", "Text"},
1385 {"skia", "Other"},
1386 };
1387 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1388 mGrContext->dumpMemoryStatistics(&gpuReporter);
1389 StringAppendF(&result, "Skia's GPU Caches: ");
1390 gpuReporter.logTotals(result);
1391 gpuReporter.logOutput(result);
1392 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1393 gpuReporter.logOutput(result, true);
1394
Alec Mouria90a5702021-04-16 16:36:21 +00001395 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1396 mGraphicBufferExternalRefs.size());
1397 StringAppendF(&result, "Dumping buffer ids...\n");
1398 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1399 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1400 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001401 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1402 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001403 StringAppendF(&result, "Dumping buffer ids...\n");
1404 // TODO(178539829): It would be nice to know which layer these are coming from and what
1405 // the texture sizes are.
1406 for (const auto& [id, unused] : mTextureCache) {
1407 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1408 }
1409 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001410
1411 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001412 if (mProtectedGrContext) {
1413 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1414 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001415 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1416 gpuProtectedReporter.logTotals(result);
1417 gpuProtectedReporter.logOutput(result);
1418 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1419 gpuProtectedReporter.logOutput(result, true);
1420
1421 StringAppendF(&result, "RenderEngine protected AHB/BackendTexture cache size: %zu\n",
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001422 mProtectedTextureCache.size());
1423 StringAppendF(&result, "Dumping buffer ids...\n");
1424 for (const auto& [id, unused] : mProtectedTextureCache) {
1425 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1426 }
1427 StringAppendF(&result, "\n");
1428 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1429 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1430 StringAppendF(&result, "- inputDataspace: %s\n",
1431 dataspaceDetails(
1432 static_cast<android_dataspace>(linearEffect.inputDataspace))
1433 .c_str());
1434 StringAppendF(&result, "- outputDataspace: %s\n",
1435 dataspaceDetails(
1436 static_cast<android_dataspace>(linearEffect.outputDataspace))
1437 .c_str());
1438 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1439 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1440 }
1441 }
1442 StringAppendF(&result, "\n");
1443}
1444
John Reck67b1e2b2020-08-26 13:17:24 -07001445} // namespace skia
1446} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001447} // namespace android