blob: fcb31968d91ee39973926db946577ca37592cf6e [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>
Alec Mourib5777452020-09-28 11:32:42 -070043
44#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080045#include <cstdint>
46#include <memory>
47
48#include "../gl/GLExtensions.h"
Alec Mouric0aae732021-01-12 13:32:18 -080049#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080050#include "SkBlendMode.h"
51#include "SkImageInfo.h"
52#include "filters/BlurFilter.h"
53#include "filters/LinearEffect.h"
54#include "log/log_main.h"
55#include "skia/debug/SkiaCapture.h"
56#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070057
John Reck67b1e2b2020-08-26 13:17:24 -070058bool checkGlError(const char* op, int lineNumber);
59
60namespace android {
61namespace renderengine {
62namespace skia {
63
Ana Krulec1d12b3b2021-01-27 16:49:51 -080064using base::StringAppendF;
65
John Reck67b1e2b2020-08-26 13:17:24 -070066static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
67 EGLint wanted, EGLConfig* outConfig) {
68 EGLint numConfigs = -1, n = 0;
69 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
70 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
71 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
72 configs.resize(n);
73
74 if (!configs.empty()) {
75 if (attribute != EGL_NONE) {
76 for (EGLConfig config : configs) {
77 EGLint value = 0;
78 eglGetConfigAttrib(dpy, config, attribute, &value);
79 if (wanted == value) {
80 *outConfig = config;
81 return NO_ERROR;
82 }
83 }
84 } else {
85 // just pick the first one
86 *outConfig = configs[0];
87 return NO_ERROR;
88 }
89 }
90
91 return NAME_NOT_FOUND;
92}
93
94static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
95 EGLConfig* config) {
96 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
97 // it is to be used with WIFI displays
98 status_t err;
99 EGLint wantedAttribute;
100 EGLint wantedAttributeValue;
101
102 std::vector<EGLint> attribs;
103 if (renderableType) {
104 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
105 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
106
107 // Default to 8 bits per channel.
108 const EGLint tmpAttribs[] = {
109 EGL_RENDERABLE_TYPE,
110 renderableType,
111 EGL_RECORDABLE_ANDROID,
112 EGL_TRUE,
113 EGL_SURFACE_TYPE,
114 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
115 EGL_FRAMEBUFFER_TARGET_ANDROID,
116 EGL_TRUE,
117 EGL_RED_SIZE,
118 is1010102 ? 10 : 8,
119 EGL_GREEN_SIZE,
120 is1010102 ? 10 : 8,
121 EGL_BLUE_SIZE,
122 is1010102 ? 10 : 8,
123 EGL_ALPHA_SIZE,
124 is1010102 ? 2 : 8,
125 EGL_NONE,
126 };
127 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
128 std::back_inserter(attribs));
129 wantedAttribute = EGL_NONE;
130 wantedAttributeValue = EGL_NONE;
131 } else {
132 // if no renderable type specified, fallback to a simplified query
133 wantedAttribute = EGL_NATIVE_VISUAL_ID;
134 wantedAttributeValue = format;
135 }
136
137 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
138 config);
139 if (err == NO_ERROR) {
140 EGLint caveat;
141 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
142 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
143 }
144
145 return err;
146}
147
148std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
149 const RenderEngineCreationArgs& args) {
150 // initialize EGL for the default display
151 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
152 if (!eglInitialize(display, nullptr, nullptr)) {
153 LOG_ALWAYS_FATAL("failed to initialize EGL");
154 }
155
Yiwei Zhange2650962020-12-01 23:27:58 +0000156 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700157 if (!eglVersion) {
158 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000159 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700160 }
161
Yiwei Zhange2650962020-12-01 23:27:58 +0000162 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700163 if (!eglExtensions) {
164 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000165 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700166 }
167
168 auto& extensions = gl::GLExtensions::getInstance();
169 extensions.initWithEGLStrings(eglVersion, eglExtensions);
170
171 // The code assumes that ES2 or later is available if this extension is
172 // supported.
173 EGLConfig config = EGL_NO_CONFIG_KHR;
174 if (!extensions.hasNoConfigContext()) {
175 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
176 }
177
John Reck67b1e2b2020-08-26 13:17:24 -0700178 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800179 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700180 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800181 protectedContext =
182 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700183 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
184 }
185
Alec Mourid6f09462020-12-07 11:18:17 -0800186 EGLContext ctxt =
187 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700188
189 // if can't create a GL context, we can only abort.
190 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
191
192 EGLSurface placeholder = EGL_NO_SURFACE;
193 if (!extensions.hasSurfacelessContext()) {
194 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
195 Protection::UNPROTECTED);
196 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
197 }
198 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
199 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
200 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
201 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
202
203 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
204 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
205 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
206 Protection::PROTECTED);
207 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
208 "can't create protected placeholder pbuffer");
209 }
210
211 // initialize the renderer while GL is current
212 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000213 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
214 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700215
216 ALOGI("OpenGL ES informations:");
217 ALOGI("vendor : %s", extensions.getVendor());
218 ALOGI("renderer : %s", extensions.getRenderer());
219 ALOGI("version : %s", extensions.getVersion());
220 ALOGI("extensions: %s", extensions.getExtensions());
221 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
222 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
223
224 return engine;
225}
226
227EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
228 status_t err;
229 EGLConfig config;
230
231 // First try to get an ES3 config
232 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
233 if (err != NO_ERROR) {
234 // If ES3 fails, try to get an ES2 config
235 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
236 if (err != NO_ERROR) {
237 // If ES2 still doesn't work, probably because we're on the emulator.
238 // try a simplified query
239 ALOGW("no suitable EGLConfig found, trying a simpler query");
240 err = selectEGLConfig(display, format, 0, &config);
241 if (err != NO_ERROR) {
242 // this EGL is too lame for android
243 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
244 }
245 }
246 }
247
248 if (logConfig) {
249 // print some debugging info
250 EGLint r, g, b, a;
251 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
252 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
253 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
254 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
255 ALOGI("EGL information:");
256 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
257 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
258 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
259 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
260 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
261 }
262
263 return config;
264}
265
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700266SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000267 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700268 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri081be4c2020-09-16 10:24:47 -0700269 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700270 mEGLContext(ctxt),
271 mPlaceholderSurface(placeholder),
272 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700273 mProtectedPlaceholderSurface(protectedPlaceholder),
Ana Krulecdfec8f52021-01-13 12:51:47 -0800274 mUseColorManagement(args.useColorManagement),
275 mRenderEngineType(args.renderEngineType) {
John Reck67b1e2b2020-08-26 13:17:24 -0700276 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
277 LOG_ALWAYS_FATAL_IF(!glInterface.get());
278
279 GrContextOptions options;
280 options.fPreferExternalImagesOverES3 = true;
281 options.fDisableDistanceFieldPaths = true;
Lucas Dupind508e472020-11-04 04:32:06 +0000282 mGrContext = GrDirectContext::MakeGL(glInterface, options);
283 if (useProtectedContext(true)) {
284 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
285 useProtectedContext(false);
286 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700287
288 if (args.supportsBackgroundBlur) {
289 mBlurFilter = new BlurFilter();
290 }
Alec Mouric0aae732021-01-12 13:32:18 -0800291 mCapture = std::make_unique<SkiaCapture>();
292}
293
294SkiaGLRenderEngine::~SkiaGLRenderEngine() {
295 std::lock_guard<std::mutex> lock(mRenderingMutex);
296 mRuntimeEffects.clear();
297 mProtectedTextureCache.clear();
298 mTextureCache.clear();
299
300 if (mBlurFilter) {
301 delete mBlurFilter;
302 }
303
304 mCapture = nullptr;
305
306 mGrContext->flushAndSubmit(true);
307 mGrContext->abandonContext();
308
309 if (mProtectedGrContext) {
310 mProtectedGrContext->flushAndSubmit(true);
311 mProtectedGrContext->abandonContext();
312 }
313
314 if (mPlaceholderSurface != EGL_NO_SURFACE) {
315 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
316 }
317 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
318 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
319 }
320 if (mEGLContext != EGL_NO_CONTEXT) {
321 eglDestroyContext(mEGLDisplay, mEGLContext);
322 }
323 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
324 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
325 }
326 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
327 eglTerminate(mEGLDisplay);
328 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700329}
330
Lucas Dupind508e472020-11-04 04:32:06 +0000331bool SkiaGLRenderEngine::supportsProtectedContent() const {
332 return mProtectedEGLContext != EGL_NO_CONTEXT;
333}
334
335bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
336 if (useProtectedContext == mInProtectedContext) {
337 return true;
338 }
339 if (useProtectedContext && supportsProtectedContent()) {
340 return false;
341 }
342 const EGLSurface surface =
343 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
344 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
345 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800346
Lucas Dupind508e472020-11-04 04:32:06 +0000347 if (success) {
348 mInProtectedContext = useProtectedContext;
349 }
350 return success;
351}
352
John Reck67b1e2b2020-08-26 13:17:24 -0700353base::unique_fd SkiaGLRenderEngine::flush() {
354 ATRACE_CALL();
355 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
356 return base::unique_fd();
357 }
358
359 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
360 if (sync == EGL_NO_SYNC_KHR) {
361 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
362 return base::unique_fd();
363 }
364
365 // native fence fd will not be populated until flush() is done.
366 glFlush();
367
368 // get the fence fd
369 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
370 eglDestroySyncKHR(mEGLDisplay, sync);
371 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
372 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
373 }
374
375 return fenceFd;
376}
377
378bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
379 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
380 !gl::GLExtensions::getInstance().hasWaitSync()) {
381 return false;
382 }
383
384 // release the fd and transfer the ownership to EGLSync
385 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
386 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
387 if (sync == EGL_NO_SYNC_KHR) {
388 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
389 return false;
390 }
391
392 // XXX: The spec draft is inconsistent as to whether this should return an
393 // EGLint or void. Ignore the return value for now, as it's not strictly
394 // needed.
395 eglWaitSyncKHR(mEGLDisplay, sync, 0);
396 EGLint error = eglGetError();
397 eglDestroySyncKHR(mEGLDisplay, sync);
398 if (error != EGL_SUCCESS) {
399 ALOGE("failed to wait for EGL native fence sync: %#x", error);
400 return false;
401 }
402
403 return true;
404}
405
406static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
407 return !!(desc.usage & usage);
408}
409
Alec Mouri678245d2020-09-30 16:58:23 -0700410static float toDegrees(uint32_t transform) {
411 switch (transform) {
412 case ui::Transform::ROT_90:
413 return 90.0;
414 case ui::Transform::ROT_180:
415 return 180.0;
416 case ui::Transform::ROT_270:
417 return 270.0;
418 default:
419 return 0.0;
420 }
421}
422
Alec Mourib34f0b72020-10-02 13:18:34 -0700423static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
424 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
425 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
426 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
427 matrix[3][3], 0);
428}
429
Alec Mouri029d1952020-10-12 10:37:08 -0700430static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
431 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
432 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
433
434 // Treat unsupported dataspaces as srgb
435 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
436 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
437 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
438 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
439 }
440
441 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
442 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
443 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
444 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
445 }
446
447 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
448 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
449 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
450 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
451
452 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
453 sourceTransfer != destTransfer;
454}
455
Alec Mouri1a4d0642020-11-13 17:42:01 -0800456static bool needsLinearEffect(const mat4& colorTransform, ui::Dataspace sourceDataspace,
457 ui::Dataspace destinationDataspace) {
458 return colorTransform != mat4() || needsToneMapping(sourceDataspace, destinationDataspace);
459}
460
Ana Krulecdfec8f52021-01-13 12:51:47 -0800461void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
462 // Only run this if RE is running on its own thread. This way the access to GL
463 // operations is guaranteed to be happening on the same thread.
464 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
465 return;
466 }
467 ATRACE_CALL();
468
469 std::lock_guard<std::mutex> lock(mRenderingMutex);
470 auto iter = mTextureCache.find(buffer->getId());
471 if (iter != mTextureCache.end()) {
472 ALOGV("Texture already exists in cache.");
473 return;
474 } else {
475 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
476 std::make_shared<AutoBackendTexture::LocalRef>();
477 imageTextureRef->setTexture(
478 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), false));
479 mTextureCache.insert({buffer->getId(), imageTextureRef});
480 }
481}
482
John Reck67b1e2b2020-08-26 13:17:24 -0700483void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800484 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700485 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800486 mTextureCache.erase(bufferId);
487 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700488}
489
Ana Krulec47814212021-01-06 19:00:10 -0800490sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
491 const LayerSettings* layer,
492 const DisplaySettings& display,
493 bool undoPremultipliedAlpha) {
John Reckcdb4ed72021-02-04 13:39:33 -0500494 if (layer->stretchEffect.hasEffect()) {
495 // TODO: Implement
496 }
Ana Krulec47814212021-01-06 19:00:10 -0800497 if (mUseColorManagement &&
498 needsLinearEffect(layer->colorTransform, layer->sourceDataspace, display.outputDataspace)) {
499 LinearEffect effect = LinearEffect{.inputDataspace = layer->sourceDataspace,
500 .outputDataspace = display.outputDataspace,
501 .undoPremultipliedAlpha = undoPremultipliedAlpha};
502
503 auto effectIter = mRuntimeEffects.find(effect);
504 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
505 if (effectIter == mRuntimeEffects.end()) {
506 runtimeEffect = buildRuntimeEffect(effect);
507 mRuntimeEffects.insert({effect, runtimeEffect});
508 } else {
509 runtimeEffect = effectIter->second;
510 }
511 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
512 display.maxLuminance,
513 layer->source.buffer.maxMasteringLuminance,
514 layer->source.buffer.maxContentLuminance);
515 }
516 return shader;
517}
518
John Reck67b1e2b2020-08-26 13:17:24 -0700519status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
520 const std::vector<const LayerSettings*>& layers,
521 const sp<GraphicBuffer>& buffer,
522 const bool useFramebufferCache,
523 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
524 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800525
John Reck67b1e2b2020-08-26 13:17:24 -0700526 std::lock_guard<std::mutex> lock(mRenderingMutex);
527 if (layers.empty()) {
528 ALOGV("Drawing empty layer stack");
529 return NO_ERROR;
530 }
531
532 if (bufferFence.get() >= 0) {
533 // Duplicate the fence for passing to waitFence.
534 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
535 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
536 ATRACE_NAME("Waiting before draw");
537 sync_wait(bufferFence.get(), -1);
538 }
539 }
540 if (buffer == nullptr) {
541 ALOGE("No output buffer provided. Aborting GPU composition.");
542 return BAD_VALUE;
543 }
544
Lucas Dupind508e472020-11-04 04:32:06 +0000545 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800546 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700547 AHardwareBuffer_Desc bufferDesc;
548 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700549 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
550 "missing usage");
551
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800552 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700553 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000554 auto iter = cache.find(buffer->getId());
555 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700556 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800557 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800558 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700559 }
560 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800561
562 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800563 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800564 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
565 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800566 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800567 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700568 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800569 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700570 }
571 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800572
573 sk_sp<SkSurface> surface =
574 surfaceTextureRef->getTexture()->getOrCreateSurface(mUseColorManagement
575 ? display.outputDataspace
Alec Mouric0aae732021-01-12 13:32:18 -0800576 : ui::Dataspace::UNKNOWN,
577 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700578
Alec Mouric0aae732021-01-12 13:32:18 -0800579 SkCanvas* canvas = mCapture->tryCapture(surface.get());
Ana Krulec6eab17a2020-12-09 15:52:36 -0800580 if (canvas == nullptr) {
581 ALOGE("Cannot acquire canvas from Skia.");
582 return BAD_VALUE;
583 }
Alec Mouri678245d2020-09-30 16:58:23 -0700584 // Clear the entire canvas with a transparent black to prevent ghost images.
585 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700586 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700587
Alec Mouric0aae732021-01-12 13:32:18 -0800588 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800589 // Record display settings when capture is running.
590 std::stringstream displaySettings;
591 PrintTo(display, &displaySettings);
592 // Store the DisplaySettings in additional information.
593 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
594 SkData::MakeWithCString(displaySettings.str().c_str()));
595 }
596
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700597 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
598 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
599 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700600
601 canvas->clipRect(getSkRect(display.physicalDisplay));
Galia Peychevaf7889b32020-11-25 22:22:40 +0100602 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700603
604 const auto clipWidth = display.clip.width();
605 const auto clipHeight = display.clip.height();
606 auto rotatedClipWidth = clipWidth;
607 auto rotatedClipHeight = clipHeight;
608 // Scale is contingent on the rotation result.
609 if (display.orientation & ui::Transform::ROT_90) {
610 std::swap(rotatedClipWidth, rotatedClipHeight);
611 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700612 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700613 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700614 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700615 static_cast<SkScalar>(rotatedClipHeight);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100616 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700617
618 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
619 // back so that the top left corner of the clip is at (0, 0).
Galia Peychevaf7889b32020-11-25 22:22:40 +0100620 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
621 canvas->rotate(toDegrees(display.orientation));
622 canvas->translate(-clipWidth / 2, -clipHeight / 2);
623 canvas->translate(-display.clip.left, -display.clip.top);
Alec Mouric0aae732021-01-12 13:32:18 -0800624
625 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
626 // view is still on-screen. The clear region could be re-specified as a black color layer,
627 // however.
628 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500629 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800630 size_t numRects = 0;
631 Rect const* rects = display.clearRegion.getArray(&numRects);
632 SkIRect skRects[numRects];
633 for (int i = 0; i < numRects; ++i) {
634 skRects[i] =
635 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
636 }
637 SkRegion clearRegion;
638 SkPaint paint;
639 sk_sp<SkShader> shader =
640 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
641 toSkColorSpace(mUseColorManagement ? display.outputDataspace
642 : ui::Dataspace::UNKNOWN));
643 paint.setShader(shader);
644 clearRegion.setRects(skRects, numRects);
645 canvas->drawRegion(clearRegion, paint);
646 }
647
John Reck67b1e2b2020-08-26 13:17:24 -0700648 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500649 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100650 canvas->save();
651
Alec Mouric0aae732021-01-12 13:32:18 -0800652 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800653 // Record the name of the layer if the capture is running.
654 std::stringstream layerSettings;
655 PrintTo(*layer, &layerSettings);
656 // Store the LayerSettings in additional information.
657 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
658 SkData::MakeWithCString(layerSettings.str().c_str()));
659 }
660
Galia Peychevaf7889b32020-11-25 22:22:40 +0100661 // Layers have a local transform that should be applied to them
662 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100663
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500664 const auto bounds = getSkRect(layer->geometry.boundaries);
665 if (mBlurFilter && layerHasBlur(layer)) {
666 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
667
668 // image to be blurred
669 sk_sp<SkImage> blurInput = surface->makeImageSnapshot();
670 // rect to be blurred in the coordinate space of blurInput
671 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
672
Lucas Dupinc3800b82020-10-02 16:24:48 -0700673 if (layer->backgroundBlurRadius > 0) {
674 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500675 auto blurredImage =
676 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
677 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100678
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500679 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
680
681 drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700682 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500683 for (auto region : layer->blurRegions) {
684 if (cachedBlurs[region.blurRadius] != nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700685 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500686 cachedBlurs[region.blurRadius] =
687 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
688 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700689 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500690 drawBlurRegion(canvas, region, blurRect, cachedBlurs[region.blurRadius]);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700691 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700692 }
693
Alec Mouric0aae732021-01-12 13:32:18 -0800694 const ui::Dataspace targetDataspace = mUseColorManagement
695 ? (needsLinearEffect(layer->colorTransform, layer->sourceDataspace,
696 display.outputDataspace)
697 // If we need to map to linear space, then mark the source image with the
698 // same colorspace as the destination surface so that Skia's color
699 // management is a no-op.
700 ? display.outputDataspace
701 : layer->sourceDataspace)
702 : ui::Dataspace::UNKNOWN;
703
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500704 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700705 if (layer->source.buffer.buffer) {
706 ATRACE_NAME("DrawImage");
707 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800708 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
709 auto iter = mTextureCache.find(item.buffer->getId());
710 if (iter != mTextureCache.end()) {
711 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700712 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800713 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800714 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800715 item.buffer->toAHardwareBuffer(),
716 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800717 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700718 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800719
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800720 sk_sp<SkImage> image =
Alec Mouric0aae732021-01-12 13:32:18 -0800721 imageTextureRef->getTexture()->makeImage(targetDataspace,
722 item.usePremultipliedAlpha
723 ? kPremul_SkAlphaType
724 : kUnpremul_SkAlphaType,
725 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700726
727 auto texMatrix = getSkM44(item.textureTransform).asM33();
728 // textureTansform was intended to be passed directly into a shader, so when
729 // building the total matrix with the textureTransform we need to first
730 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500731 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800732 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700733
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800734 SkMatrix matrix;
735 if (!texMatrix.invert(&matrix)) {
736 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700737 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800738 // The shader does not respect the translation, so we add it to the texture
739 // transform for the SkImage. This will make sure that the correct layer contents
740 // are drawn in the correct part of the screen.
741 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700742
Ana Krulecb7b28b22020-11-23 14:48:58 -0800743 sk_sp<SkShader> shader;
744
745 if (layer->source.buffer.useTextureFiltering) {
746 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
747 SkSamplingOptions(
748 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
749 &matrix);
750 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500751 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800752 }
Alec Mouri029d1952020-10-12 10:37:08 -0700753
Alec Mouric0aae732021-01-12 13:32:18 -0800754 // Handle opaque images - it's a little nonstandard how we do this.
755 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
756 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
757 // The important language is that when isOpaque is set, opacity is not sampled from the
758 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
759 // here's the conundrum:
760 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
761 // as an internal hint - composition is undefined when there are alpha bits present.
762 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
763 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
764 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
765 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
766 // of a hack anyways.
767 // 3. We can't change the blendmode to src, because while this satisfies the requirement
768 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
769 // because src always clobbers the destination content.
770 //
771 // So, what we do here instead is an additive blend mode where we compose the input
772 // image with a solid black. This might need to be reassess if this does not support
773 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
774 if (item.isOpaque) {
775 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
776 SkShaders::Color(SkColors::kBlack,
777 toSkColorSpace(targetDataspace)));
778 }
779
Ana Krulec47814212021-01-06 19:00:10 -0800780 paint.setShader(
781 createRuntimeEffectShader(shader, layer, display,
782 !item.isOpaque && item.usePremultipliedAlpha));
Ana Krulec1768bd22020-11-23 14:51:31 -0800783 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700784 } else {
785 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700786 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800787 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
788 .fG = color.g,
789 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800790 .fA = layer->alpha},
791 toSkColorSpace(targetDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800792 paint.setShader(createRuntimeEffectShader(shader, layer, display,
793 /* undoPremultipliedAlpha */ false));
John Reck67b1e2b2020-08-26 13:17:24 -0700794 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700795
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800796 sk_sp<SkColorFilter> filter =
797 SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
798
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800799 paint.setColorFilter(filter);
Alec Mourib34f0b72020-10-02 13:18:34 -0700800
Lucas Dupin3f11e922020-09-22 17:31:04 -0700801 if (layer->shadow.length > 0) {
802 const auto rect = layer->geometry.roundedCornersRadius > 0
803 ? getSkRect(layer->geometry.roundedCornersCrop)
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500804 : bounds;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700805 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800806 } else {
807 // Shadows are assumed to live only on their own layer - it's not valid
808 // to draw the boundary retangles when there is already a caster shadow
809 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
810 // composition - using a well-defined invalid color is long-term less error-prone.
811 // Push the clipRRect onto the clip stack. Draw the image. Pop the clip.
812 if (layer->geometry.roundedCornersRadius > 0) {
813 canvas->clipRRect(getRoundedRect(layer), true);
814 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500815 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700816 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700817 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700818 }
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800819 canvas->restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800820 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700821 {
822 ATRACE_NAME("flush surface");
823 surface->flush();
824 }
825
826 if (drawFence != nullptr) {
827 *drawFence = flush();
828 }
829
830 // If flush failed or we don't support native fences, we need to force the
831 // gl command stream to be executed.
832 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
833 if (requireSync) {
834 ATRACE_BEGIN("Submit(sync=true)");
835 } else {
836 ATRACE_BEGIN("Submit(sync=false)");
837 }
Lucas Dupind508e472020-11-04 04:32:06 +0000838 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700839 ATRACE_END();
840 if (!success) {
841 ALOGE("Failed to flush RenderEngine commands");
842 // Chances are, something illegal happened (either the caller passed
843 // us bad parameters, or we messed up our shader generation).
844 return INVALID_OPERATION;
845 }
846
847 // checkErrors();
848 return NO_ERROR;
849}
850
Lucas Dupin3f11e922020-09-22 17:31:04 -0700851inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
852 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
853}
854
855inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
856 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
857}
858
Lucas Dupin21f348e2020-09-16 17:31:26 -0700859inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800860 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700861 const auto cornerRadius = layer->geometry.roundedCornersRadius;
862 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
863}
864
Galia Peycheva80116e52020-11-06 11:57:25 +0100865inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
866 const auto rect = getSkRect(layer->geometry.boundaries);
867 const auto cornersRadius = layer->geometry.roundedCornersRadius;
868 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
869 .cornerRadiusTL = cornersRadius,
870 .cornerRadiusTR = cornersRadius,
871 .cornerRadiusBL = cornersRadius,
872 .cornerRadiusBR = cornersRadius,
873 .alpha = 1,
874 .left = static_cast<int>(rect.fLeft),
875 .top = static_cast<int>(rect.fTop),
876 .right = static_cast<int>(rect.fRight),
877 .bottom = static_cast<int>(rect.fBottom)};
878}
879
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500880inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
881 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
882}
883
Lucas Dupin3f11e922020-09-22 17:31:04 -0700884inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
885 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
886}
887
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700888inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
889 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
890 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
891 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
892 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
893}
894
Lucas Dupin3f11e922020-09-22 17:31:04 -0700895inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
896 return SkPoint3::Make(vector.x, vector.y, vector.z);
897}
898
John Reck67b1e2b2020-08-26 13:17:24 -0700899size_t SkiaGLRenderEngine::getMaxTextureSize() const {
900 return mGrContext->maxTextureSize();
901}
902
903size_t SkiaGLRenderEngine::getMaxViewportDims() const {
904 return mGrContext->maxRenderTargetSize();
905}
906
Lucas Dupin3f11e922020-09-22 17:31:04 -0700907void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
908 const ShadowSettings& settings) {
909 ATRACE_CALL();
910 const float casterZ = settings.length / 2.0f;
911 const auto shadowShape = cornerRadius > 0
912 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
913 : SkPath::Rect(casterRect);
914 const auto flags =
915 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
916
917 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
918 getSkPoint3(settings.lightPos), settings.lightRadius,
919 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
920 flags);
921}
922
Lucas Dupinc3800b82020-10-02 16:24:48 -0700923void SkiaGLRenderEngine::drawBlurRegion(SkCanvas* canvas, const BlurRegion& effectRegion,
Derek Sollenberger545ec442021-01-25 10:02:23 -0500924 const SkRect& layerRect, sk_sp<SkImage> blurredImage) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700925 ATRACE_CALL();
Galia Peycheva80116e52020-11-06 11:57:25 +0100926
Lucas Dupinc3800b82020-10-02 16:24:48 -0700927 SkPaint paint;
Lyn Han1bdedb32020-11-23 20:33:57 +0000928 paint.setAlpha(static_cast<int>(effectRegion.alpha * 255));
Robin Leef180f412020-12-07 02:51:41 +0100929 const auto matrix = getBlurShaderTransform(canvas, layerRect);
Derek Sollenberger545ec442021-01-25 10:02:23 -0500930 SkSamplingOptions linearSampling(SkFilterMode::kLinear, SkMipmapMode::kNone);
931 paint.setShader(blurredImage->makeShader(SkTileMode::kClamp, SkTileMode::kClamp, linearSampling,
932 &matrix));
Lucas Dupinc3800b82020-10-02 16:24:48 -0700933
Galia Peycheva80116e52020-11-06 11:57:25 +0100934 auto rect = SkRect::MakeLTRB(effectRegion.left, effectRegion.top, effectRegion.right,
935 effectRegion.bottom);
Galia Peycheva80116e52020-11-06 11:57:25 +0100936
Lucas Dupinc3800b82020-10-02 16:24:48 -0700937 if (effectRegion.cornerRadiusTL > 0 || effectRegion.cornerRadiusTR > 0 ||
938 effectRegion.cornerRadiusBL > 0 || effectRegion.cornerRadiusBR > 0) {
939 const SkVector radii[4] =
940 {SkVector::Make(effectRegion.cornerRadiusTL, effectRegion.cornerRadiusTL),
941 SkVector::Make(effectRegion.cornerRadiusTR, effectRegion.cornerRadiusTR),
942 SkVector::Make(effectRegion.cornerRadiusBL, effectRegion.cornerRadiusBL),
943 SkVector::Make(effectRegion.cornerRadiusBR, effectRegion.cornerRadiusBR)};
944 SkRRect roundedRect;
945 roundedRect.setRectRadii(rect, radii);
946 canvas->drawRRect(roundedRect, paint);
947 } else {
948 canvas->drawRect(rect, paint);
949 }
950}
951
Galia Peychevaf7889b32020-11-25 22:22:40 +0100952SkMatrix SkiaGLRenderEngine::getBlurShaderTransform(const SkCanvas* canvas,
953 const SkRect& layerRect) {
954 // 1. Apply the blur shader matrix, which scales up the blured surface to its real size
955 auto matrix = mBlurFilter->getShaderMatrix();
956 // 2. Since the blurred surface has the size of the layer, we align it with the
957 // top left corner of the layer position.
958 matrix.postConcat(SkMatrix::Translate(layerRect.fLeft, layerRect.fTop));
959 // 3. Finally, apply the inverse canvas matrix. The snapshot made in the BlurFilter is in the
960 // original surface orientation. The inverse matrix has to be applied to align the blur
961 // surface with the current orientation/position of the canvas.
962 SkMatrix drawInverse;
963 if (canvas->getTotalMatrix().invert(&drawInverse)) {
964 matrix.postConcat(drawInverse);
965 }
966
967 return matrix;
968}
969
John Reck67b1e2b2020-08-26 13:17:24 -0700970EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -0800971 EGLContext shareContext,
972 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -0700973 Protection protection) {
974 EGLint renderableType = 0;
975 if (config == EGL_NO_CONFIG_KHR) {
976 renderableType = EGL_OPENGL_ES3_BIT;
977 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
978 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
979 }
980 EGLint contextClientVersion = 0;
981 if (renderableType & EGL_OPENGL_ES3_BIT) {
982 contextClientVersion = 3;
983 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
984 contextClientVersion = 2;
985 } else if (renderableType & EGL_OPENGL_ES_BIT) {
986 contextClientVersion = 1;
987 } else {
988 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
989 }
990
991 std::vector<EGLint> contextAttributes;
992 contextAttributes.reserve(7);
993 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
994 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -0800995 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -0700996 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -0800997 switch (*contextPriority) {
998 case ContextPriority::REALTIME:
999 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1000 break;
1001 case ContextPriority::MEDIUM:
1002 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1003 break;
1004 case ContextPriority::LOW:
1005 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1006 break;
1007 case ContextPriority::HIGH:
1008 default:
1009 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1010 break;
1011 }
John Reck67b1e2b2020-08-26 13:17:24 -07001012 }
1013 if (protection == Protection::PROTECTED) {
1014 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1015 contextAttributes.push_back(EGL_TRUE);
1016 }
1017 contextAttributes.push_back(EGL_NONE);
1018
1019 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1020
1021 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1022 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1023 // EGL_NO_CONTEXT so that we can abort.
1024 if (config != EGL_NO_CONFIG_KHR) {
1025 return context;
1026 }
1027 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1028 // should try to fall back to GLES 2.
1029 contextAttributes[1] = 2;
1030 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1031 }
1032
1033 return context;
1034}
1035
Alec Mourid6f09462020-12-07 11:18:17 -08001036std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1037 const RenderEngineCreationArgs& args) {
1038 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1039 return std::nullopt;
1040 }
1041
1042 switch (args.contextPriority) {
1043 case RenderEngine::ContextPriority::REALTIME:
1044 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1045 return RenderEngine::ContextPriority::REALTIME;
1046 } else {
1047 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1048 return RenderEngine::ContextPriority::HIGH;
1049 }
1050 case RenderEngine::ContextPriority::HIGH:
1051 case RenderEngine::ContextPriority::MEDIUM:
1052 case RenderEngine::ContextPriority::LOW:
1053 return args.contextPriority;
1054 default:
1055 return std::nullopt;
1056 }
1057}
1058
John Reck67b1e2b2020-08-26 13:17:24 -07001059EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1060 EGLConfig config, int hwcFormat,
1061 Protection protection) {
1062 EGLConfig placeholderConfig = config;
1063 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1064 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1065 }
1066 std::vector<EGLint> attributes;
1067 attributes.reserve(7);
1068 attributes.push_back(EGL_WIDTH);
1069 attributes.push_back(1);
1070 attributes.push_back(EGL_HEIGHT);
1071 attributes.push_back(1);
1072 if (protection == Protection::PROTECTED) {
1073 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1074 attributes.push_back(EGL_TRUE);
1075 }
1076 attributes.push_back(EGL_NONE);
1077
1078 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1079}
1080
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001081void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -07001082
Alec Mourid6f09462020-12-07 11:18:17 -08001083int SkiaGLRenderEngine::getContextPriority() {
1084 int value;
1085 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1086 return value;
1087}
1088
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001089void SkiaGLRenderEngine::dump(std::string& result) {
1090 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1091
1092 StringAppendF(&result, "\n ------------RE-----------------\n");
1093 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1094 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1095 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1096 extensions.getVersion());
1097 StringAppendF(&result, "%s\n", extensions.getExtensions());
1098 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1099 supportsProtectedContent());
1100 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1101
1102 {
1103 std::lock_guard<std::mutex> lock(mRenderingMutex);
1104 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1105 StringAppendF(&result, "Dumping buffer ids...\n");
1106 // TODO(178539829): It would be nice to know which layer these are coming from and what
1107 // the texture sizes are.
1108 for (const auto& [id, unused] : mTextureCache) {
1109 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1110 }
1111 StringAppendF(&result, "\n");
1112 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1113 mProtectedTextureCache.size());
1114 StringAppendF(&result, "Dumping buffer ids...\n");
1115 for (const auto& [id, unused] : mProtectedTextureCache) {
1116 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1117 }
1118 StringAppendF(&result, "\n");
1119 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1120 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1121 StringAppendF(&result, "- inputDataspace: %s\n",
1122 dataspaceDetails(
1123 static_cast<android_dataspace>(linearEffect.inputDataspace))
1124 .c_str());
1125 StringAppendF(&result, "- outputDataspace: %s\n",
1126 dataspaceDetails(
1127 static_cast<android_dataspace>(linearEffect.outputDataspace))
1128 .c_str());
1129 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1130 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1131 }
1132 }
1133 StringAppendF(&result, "\n");
1134}
1135
John Reck67b1e2b2020-08-26 13:17:24 -07001136} // namespace skia
1137} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001138} // namespace android