blob: 9f400114119db928d9cdd0150c339a68e7df03e6 [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) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500289 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700290 mBlurFilter = new BlurFilter();
291 }
Alec Mouric0aae732021-01-12 13:32:18 -0800292 mCapture = std::make_unique<SkiaCapture>();
293}
294
295SkiaGLRenderEngine::~SkiaGLRenderEngine() {
296 std::lock_guard<std::mutex> lock(mRenderingMutex);
297 mRuntimeEffects.clear();
298 mProtectedTextureCache.clear();
299 mTextureCache.clear();
300
301 if (mBlurFilter) {
302 delete mBlurFilter;
303 }
304
305 mCapture = nullptr;
306
307 mGrContext->flushAndSubmit(true);
308 mGrContext->abandonContext();
309
310 if (mProtectedGrContext) {
311 mProtectedGrContext->flushAndSubmit(true);
312 mProtectedGrContext->abandonContext();
313 }
314
315 if (mPlaceholderSurface != EGL_NO_SURFACE) {
316 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
317 }
318 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
319 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
320 }
321 if (mEGLContext != EGL_NO_CONTEXT) {
322 eglDestroyContext(mEGLDisplay, mEGLContext);
323 }
324 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
325 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
326 }
327 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
328 eglTerminate(mEGLDisplay);
329 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700330}
331
Lucas Dupind508e472020-11-04 04:32:06 +0000332bool SkiaGLRenderEngine::supportsProtectedContent() const {
333 return mProtectedEGLContext != EGL_NO_CONTEXT;
334}
335
336bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
337 if (useProtectedContext == mInProtectedContext) {
338 return true;
339 }
Alec Mourif6a07812021-02-11 21:07:55 -0800340 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000341 return false;
342 }
343 const EGLSurface surface =
344 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
345 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
346 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800347
Lucas Dupind508e472020-11-04 04:32:06 +0000348 if (success) {
349 mInProtectedContext = useProtectedContext;
350 }
351 return success;
352}
353
John Reck67b1e2b2020-08-26 13:17:24 -0700354base::unique_fd SkiaGLRenderEngine::flush() {
355 ATRACE_CALL();
356 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
357 return base::unique_fd();
358 }
359
360 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
361 if (sync == EGL_NO_SYNC_KHR) {
362 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
363 return base::unique_fd();
364 }
365
366 // native fence fd will not be populated until flush() is done.
367 glFlush();
368
369 // get the fence fd
370 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
371 eglDestroySyncKHR(mEGLDisplay, sync);
372 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
373 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
374 }
375
376 return fenceFd;
377}
378
379bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
380 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
381 !gl::GLExtensions::getInstance().hasWaitSync()) {
382 return false;
383 }
384
385 // release the fd and transfer the ownership to EGLSync
386 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
387 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
388 if (sync == EGL_NO_SYNC_KHR) {
389 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
390 return false;
391 }
392
393 // XXX: The spec draft is inconsistent as to whether this should return an
394 // EGLint or void. Ignore the return value for now, as it's not strictly
395 // needed.
396 eglWaitSyncKHR(mEGLDisplay, sync, 0);
397 EGLint error = eglGetError();
398 eglDestroySyncKHR(mEGLDisplay, sync);
399 if (error != EGL_SUCCESS) {
400 ALOGE("failed to wait for EGL native fence sync: %#x", error);
401 return false;
402 }
403
404 return true;
405}
406
407static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
408 return !!(desc.usage & usage);
409}
410
Alec Mouri678245d2020-09-30 16:58:23 -0700411static float toDegrees(uint32_t transform) {
412 switch (transform) {
413 case ui::Transform::ROT_90:
414 return 90.0;
415 case ui::Transform::ROT_180:
416 return 180.0;
417 case ui::Transform::ROT_270:
418 return 270.0;
419 default:
420 return 0.0;
421 }
422}
423
Alec Mourib34f0b72020-10-02 13:18:34 -0700424static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
425 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
426 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
427 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
428 matrix[3][3], 0);
429}
430
Alec Mouri029d1952020-10-12 10:37:08 -0700431static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
432 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
433 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
434
435 // Treat unsupported dataspaces as srgb
436 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
437 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
438 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
439 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
440 }
441
442 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
443 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
444 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
445 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
446 }
447
448 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
449 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
450 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
451 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
452
453 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
454 sourceTransfer != destTransfer;
455}
456
Ana Krulecdfec8f52021-01-13 12:51:47 -0800457void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
458 // Only run this if RE is running on its own thread. This way the access to GL
459 // operations is guaranteed to be happening on the same thread.
460 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
461 return;
462 }
463 ATRACE_CALL();
464
465 std::lock_guard<std::mutex> lock(mRenderingMutex);
466 auto iter = mTextureCache.find(buffer->getId());
467 if (iter != mTextureCache.end()) {
468 ALOGV("Texture already exists in cache.");
469 return;
470 } else {
471 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
472 std::make_shared<AutoBackendTexture::LocalRef>();
473 imageTextureRef->setTexture(
474 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), false));
475 mTextureCache.insert({buffer->getId(), imageTextureRef});
476 }
477}
478
John Reck67b1e2b2020-08-26 13:17:24 -0700479void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800480 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700481 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800482 mTextureCache.erase(bufferId);
483 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700484}
485
Ana Krulec47814212021-01-06 19:00:10 -0800486sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
487 const LayerSettings* layer,
488 const DisplaySettings& display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500489 bool undoPremultipliedAlpha,
490 bool requiresLinearEffect) {
John Reckcdb4ed72021-02-04 13:39:33 -0500491 if (layer->stretchEffect.hasEffect()) {
492 // TODO: Implement
493 }
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500494 if (requiresLinearEffect) {
495 const ui::Dataspace inputDataspace =
496 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
497 const ui::Dataspace outputDataspace =
498 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
499
500 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
501 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800502 .undoPremultipliedAlpha = undoPremultipliedAlpha};
503
504 auto effectIter = mRuntimeEffects.find(effect);
505 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
506 if (effectIter == mRuntimeEffects.end()) {
507 runtimeEffect = buildRuntimeEffect(effect);
508 mRuntimeEffects.insert({effect, runtimeEffect});
509 } else {
510 runtimeEffect = effectIter->second;
511 }
512 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
513 display.maxLuminance,
514 layer->source.buffer.maxMasteringLuminance,
515 layer->source.buffer.maxContentLuminance);
516 }
517 return shader;
518}
519
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500520void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500521 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500522 // Record display settings when capture is running.
523 std::stringstream displaySettings;
524 PrintTo(display, &displaySettings);
525 // Store the DisplaySettings in additional information.
526 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
527 SkData::MakeWithCString(displaySettings.str().c_str()));
528 }
529
530 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
531 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
532 // displays might have different scaling when compared to the physical screen.
533
534 canvas->clipRect(getSkRect(display.physicalDisplay));
535 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
536
537 const auto clipWidth = display.clip.width();
538 const auto clipHeight = display.clip.height();
539 auto rotatedClipWidth = clipWidth;
540 auto rotatedClipHeight = clipHeight;
541 // Scale is contingent on the rotation result.
542 if (display.orientation & ui::Transform::ROT_90) {
543 std::swap(rotatedClipWidth, rotatedClipHeight);
544 }
545 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
546 static_cast<SkScalar>(rotatedClipWidth);
547 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
548 static_cast<SkScalar>(rotatedClipHeight);
549 canvas->scale(scaleX, scaleY);
550
551 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
552 // back so that the top left corner of the clip is at (0, 0).
553 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
554 canvas->rotate(toDegrees(display.orientation));
555 canvas->translate(-clipWidth / 2, -clipHeight / 2);
556 canvas->translate(-display.clip.left, -display.clip.top);
557}
558
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500559class AutoSaveRestore {
560public:
561 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
562 ~AutoSaveRestore() { restore(); }
563 void replace(SkCanvas* canvas) {
564 mCanvas = canvas;
565 mSaveCount = canvas->save();
566 }
567 void restore() {
568 if (mCanvas) {
569 mCanvas->restoreToCount(mSaveCount);
570 mCanvas = nullptr;
571 }
572 }
573
574private:
575 SkCanvas* mCanvas;
576 int mSaveCount;
577};
578
John Reck67b1e2b2020-08-26 13:17:24 -0700579status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
580 const std::vector<const LayerSettings*>& layers,
581 const sp<GraphicBuffer>& buffer,
582 const bool useFramebufferCache,
583 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
584 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800585
John Reck67b1e2b2020-08-26 13:17:24 -0700586 std::lock_guard<std::mutex> lock(mRenderingMutex);
587 if (layers.empty()) {
588 ALOGV("Drawing empty layer stack");
589 return NO_ERROR;
590 }
591
592 if (bufferFence.get() >= 0) {
593 // Duplicate the fence for passing to waitFence.
594 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
595 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
596 ATRACE_NAME("Waiting before draw");
597 sync_wait(bufferFence.get(), -1);
598 }
599 }
600 if (buffer == nullptr) {
601 ALOGE("No output buffer provided. Aborting GPU composition.");
602 return BAD_VALUE;
603 }
604
Lucas Dupind508e472020-11-04 04:32:06 +0000605 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800606 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700607 AHardwareBuffer_Desc bufferDesc;
608 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700609 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
610 "missing usage");
611
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800612 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700613 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000614 auto iter = cache.find(buffer->getId());
615 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700616 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800617 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800618 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700619 }
620 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800621
622 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800623 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800624 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
625 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800626 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800627 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700628 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800629 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700630 }
631 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800632
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500633 const ui::Dataspace dstDataspace =
634 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500635 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500636 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700637
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500638 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
639 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800640 ALOGE("Cannot acquire canvas from Skia.");
641 return BAD_VALUE;
642 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500643
644 // Find if any layers have requested blur, we'll use that info to decide when to render to an
645 // offscreen buffer and when to render to the native buffer.
646 sk_sp<SkSurface> activeSurface(dstSurface);
647 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500648 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500649 const LayerSettings* blurCompositionLayer = nullptr;
650 if (mBlurFilter) {
651 bool requiresCompositionLayer = false;
652 for (const auto& layer : layers) {
653 if (layer->backgroundBlurRadius > 0) {
654 // when skbug.com/11208 and b/176903027 are resolved we can add the additional
655 // restriction for layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius
656 requiresCompositionLayer = true;
657 }
658 for (auto region : layer->blurRegions) {
659 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
660 requiresCompositionLayer = true;
661 }
662 }
663 if (requiresCompositionLayer) {
664 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500665 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500666 blurCompositionLayer = layer;
667 break;
668 }
669 }
670 }
671
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500672 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700673 // Clear the entire canvas with a transparent black to prevent ghost images.
674 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500675 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800676
677 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
678 // view is still on-screen. The clear region could be re-specified as a black color layer,
679 // however.
680 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500681 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800682 size_t numRects = 0;
683 Rect const* rects = display.clearRegion.getArray(&numRects);
684 SkIRect skRects[numRects];
685 for (int i = 0; i < numRects; ++i) {
686 skRects[i] =
687 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
688 }
689 SkRegion clearRegion;
690 SkPaint paint;
691 sk_sp<SkShader> shader =
692 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500693 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800694 paint.setShader(shader);
695 clearRegion.setRects(skRects, numRects);
696 canvas->drawRegion(clearRegion, paint);
697 }
698
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500699 // setup color filter if necessary
700 sk_sp<SkColorFilter> displayColorTransform;
701 if (display.colorTransform != mat4()) {
702 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
703 }
704
John Reck67b1e2b2020-08-26 13:17:24 -0700705 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500706 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100707
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500708 sk_sp<SkImage> blurInput;
709 if (blurCompositionLayer == layer) {
710 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
711 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
712
713 // save a snapshot of the activeSurface to use as input to the blur shaders
714 blurInput = activeSurface->makeImageSnapshot();
715
716 // TODO we could skip this step if we know the blur will cover the entire image
717 // blit the offscreen framebuffer into the destination AHB
718 SkPaint paint;
719 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500720 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
721 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
722 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
723 String8::format("SurfaceID|%" PRId64, id).c_str(),
724 nullptr);
725 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
726 } else {
727 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
728 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500729
730 // assign dstCanvas to canvas and ensure that the canvas state is up to date
731 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500732 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500733 initCanvas(canvas, display);
734
735 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
736 dstSurface->getCanvas()->getSaveCount());
737 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
738 dstSurface->getCanvas()->getTotalMatrix());
739
740 // assign dstSurface to activeSurface
741 activeSurface = dstSurface;
742 }
743
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500744 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500745 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800746 // Record the name of the layer if the capture is running.
747 std::stringstream layerSettings;
748 PrintTo(*layer, &layerSettings);
749 // Store the LayerSettings in additional information.
750 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
751 SkData::MakeWithCString(layerSettings.str().c_str()));
752 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100753 // Layers have a local transform that should be applied to them
754 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100755
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500756 const auto bounds = getSkRect(layer->geometry.boundaries);
757 if (mBlurFilter && layerHasBlur(layer)) {
758 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
759
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500760 // if multiple layers have blur, then we need to take a snapshot now because
761 // only the lowest layer will have blurImage populated earlier
762 if (!blurInput) {
763 blurInput = activeSurface->makeImageSnapshot();
764 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500765 // rect to be blurred in the coordinate space of blurInput
766 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
767
Lucas Dupinc3800b82020-10-02 16:24:48 -0700768 if (layer->backgroundBlurRadius > 0) {
769 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500770 auto blurredImage =
771 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
772 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100773
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500774 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
775
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500776 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
777 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700778 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500779 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100780 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700781 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500782 cachedBlurs[region.blurRadius] =
783 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
784 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700785 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500786
787 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
788 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700789 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700790 }
791
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500792 // Shadows are assumed to live only on their own layer - it's not valid
793 // to draw the boundary rectangles when there is already a caster shadow
794 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
795 // composition - using a well-defined invalid color is long-term less error-prone.
796 if (layer->shadow.length > 0) {
797 const auto rect = layer->geometry.roundedCornersRadius > 0
798 ? getSkRect(layer->geometry.roundedCornersCrop)
799 : bounds;
800 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
801 continue;
802 }
803
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500804 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
805 (mUseColorManagement &&
806 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
807
808 // quick abort from drawing the remaining portion of the layer
809 if (layer->alpha == 0 && !requiresLinearEffect &&
810 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
811 continue;
812 }
813
814 // If we need to map to linear space or color management is disabled, then mark the source
815 // image with the same colorspace as the destination surface so that Skia's color
816 // management is a no-op.
817 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
818 ? dstDataspace
819 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800820
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500821 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700822 if (layer->source.buffer.buffer) {
823 ATRACE_NAME("DrawImage");
824 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800825 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
826 auto iter = mTextureCache.find(item.buffer->getId());
827 if (iter != mTextureCache.end()) {
828 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700829 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800830 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800831 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800832 item.buffer->toAHardwareBuffer(),
833 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800834 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700835 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800836
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800837 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500838 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800839 item.usePremultipliedAlpha
840 ? kPremul_SkAlphaType
841 : kUnpremul_SkAlphaType,
842 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700843
844 auto texMatrix = getSkM44(item.textureTransform).asM33();
845 // textureTansform was intended to be passed directly into a shader, so when
846 // building the total matrix with the textureTransform we need to first
847 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500848 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800849 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700850
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800851 SkMatrix matrix;
852 if (!texMatrix.invert(&matrix)) {
853 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700854 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800855 // The shader does not respect the translation, so we add it to the texture
856 // transform for the SkImage. This will make sure that the correct layer contents
857 // are drawn in the correct part of the screen.
858 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700859
Ana Krulecb7b28b22020-11-23 14:48:58 -0800860 sk_sp<SkShader> shader;
861
862 if (layer->source.buffer.useTextureFiltering) {
863 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
864 SkSamplingOptions(
865 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
866 &matrix);
867 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500868 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800869 }
Alec Mouri029d1952020-10-12 10:37:08 -0700870
Alec Mouric0aae732021-01-12 13:32:18 -0800871 // Handle opaque images - it's a little nonstandard how we do this.
872 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
873 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
874 // The important language is that when isOpaque is set, opacity is not sampled from the
875 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
876 // here's the conundrum:
877 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
878 // as an internal hint - composition is undefined when there are alpha bits present.
879 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
880 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
881 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
882 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
883 // of a hack anyways.
884 // 3. We can't change the blendmode to src, because while this satisfies the requirement
885 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
886 // because src always clobbers the destination content.
887 //
888 // So, what we do here instead is an additive blend mode where we compose the input
889 // image with a solid black. This might need to be reassess if this does not support
890 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
891 if (item.isOpaque) {
892 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
893 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500894 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800895 }
896
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500897 paint.setShader(createRuntimeEffectShader(shader, layer, display,
898 !item.isOpaque && item.usePremultipliedAlpha,
899 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800900 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700901 } else {
902 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700903 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800904 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
905 .fG = color.g,
906 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800907 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500908 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800909 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500910 /* undoPremultipliedAlpha */ false,
911 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700912 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700913
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500914 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700915
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500916 if (layer->geometry.roundedCornersRadius > 0) {
917 paint.setAntiAlias(true);
918 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800919 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500920 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700921 }
John Reck67b1e2b2020-08-26 13:17:24 -0700922 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500923 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800924 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700925 {
926 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500927 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
928 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700929 }
930
931 if (drawFence != nullptr) {
932 *drawFence = flush();
933 }
934
935 // If flush failed or we don't support native fences, we need to force the
936 // gl command stream to be executed.
937 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
938 if (requireSync) {
939 ATRACE_BEGIN("Submit(sync=true)");
940 } else {
941 ATRACE_BEGIN("Submit(sync=false)");
942 }
Lucas Dupind508e472020-11-04 04:32:06 +0000943 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700944 ATRACE_END();
945 if (!success) {
946 ALOGE("Failed to flush RenderEngine commands");
947 // Chances are, something illegal happened (either the caller passed
948 // us bad parameters, or we messed up our shader generation).
949 return INVALID_OPERATION;
950 }
951
952 // checkErrors();
953 return NO_ERROR;
954}
955
Lucas Dupin3f11e922020-09-22 17:31:04 -0700956inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
957 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
958}
959
960inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
961 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
962}
963
Lucas Dupin21f348e2020-09-16 17:31:26 -0700964inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800965 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700966 const auto cornerRadius = layer->geometry.roundedCornersRadius;
967 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
968}
969
Galia Peycheva80116e52020-11-06 11:57:25 +0100970inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
971 const auto rect = getSkRect(layer->geometry.boundaries);
972 const auto cornersRadius = layer->geometry.roundedCornersRadius;
973 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
974 .cornerRadiusTL = cornersRadius,
975 .cornerRadiusTR = cornersRadius,
976 .cornerRadiusBL = cornersRadius,
977 .cornerRadiusBR = cornersRadius,
978 .alpha = 1,
979 .left = static_cast<int>(rect.fLeft),
980 .top = static_cast<int>(rect.fTop),
981 .right = static_cast<int>(rect.fRight),
982 .bottom = static_cast<int>(rect.fBottom)};
983}
984
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500985inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
986 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
987}
988
Lucas Dupin3f11e922020-09-22 17:31:04 -0700989inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
990 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
991}
992
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700993inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
994 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
995 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
996 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
997 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
998}
999
Lucas Dupin3f11e922020-09-22 17:31:04 -07001000inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1001 return SkPoint3::Make(vector.x, vector.y, vector.z);
1002}
1003
John Reck67b1e2b2020-08-26 13:17:24 -07001004size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1005 return mGrContext->maxTextureSize();
1006}
1007
1008size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1009 return mGrContext->maxRenderTargetSize();
1010}
1011
Lucas Dupin3f11e922020-09-22 17:31:04 -07001012void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1013 const ShadowSettings& settings) {
1014 ATRACE_CALL();
1015 const float casterZ = settings.length / 2.0f;
1016 const auto shadowShape = cornerRadius > 0
1017 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1018 : SkPath::Rect(casterRect);
1019 const auto flags =
1020 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1021
1022 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1023 getSkPoint3(settings.lightPos), settings.lightRadius,
1024 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1025 flags);
1026}
1027
John Reck67b1e2b2020-08-26 13:17:24 -07001028EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001029 EGLContext shareContext,
1030 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001031 Protection protection) {
1032 EGLint renderableType = 0;
1033 if (config == EGL_NO_CONFIG_KHR) {
1034 renderableType = EGL_OPENGL_ES3_BIT;
1035 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1036 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1037 }
1038 EGLint contextClientVersion = 0;
1039 if (renderableType & EGL_OPENGL_ES3_BIT) {
1040 contextClientVersion = 3;
1041 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1042 contextClientVersion = 2;
1043 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1044 contextClientVersion = 1;
1045 } else {
1046 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1047 }
1048
1049 std::vector<EGLint> contextAttributes;
1050 contextAttributes.reserve(7);
1051 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1052 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001053 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001054 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001055 switch (*contextPriority) {
1056 case ContextPriority::REALTIME:
1057 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1058 break;
1059 case ContextPriority::MEDIUM:
1060 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1061 break;
1062 case ContextPriority::LOW:
1063 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1064 break;
1065 case ContextPriority::HIGH:
1066 default:
1067 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1068 break;
1069 }
John Reck67b1e2b2020-08-26 13:17:24 -07001070 }
1071 if (protection == Protection::PROTECTED) {
1072 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1073 contextAttributes.push_back(EGL_TRUE);
1074 }
1075 contextAttributes.push_back(EGL_NONE);
1076
1077 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1078
1079 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1080 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1081 // EGL_NO_CONTEXT so that we can abort.
1082 if (config != EGL_NO_CONFIG_KHR) {
1083 return context;
1084 }
1085 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1086 // should try to fall back to GLES 2.
1087 contextAttributes[1] = 2;
1088 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1089 }
1090
1091 return context;
1092}
1093
Alec Mourid6f09462020-12-07 11:18:17 -08001094std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1095 const RenderEngineCreationArgs& args) {
1096 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1097 return std::nullopt;
1098 }
1099
1100 switch (args.contextPriority) {
1101 case RenderEngine::ContextPriority::REALTIME:
1102 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1103 return RenderEngine::ContextPriority::REALTIME;
1104 } else {
1105 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1106 return RenderEngine::ContextPriority::HIGH;
1107 }
1108 case RenderEngine::ContextPriority::HIGH:
1109 case RenderEngine::ContextPriority::MEDIUM:
1110 case RenderEngine::ContextPriority::LOW:
1111 return args.contextPriority;
1112 default:
1113 return std::nullopt;
1114 }
1115}
1116
John Reck67b1e2b2020-08-26 13:17:24 -07001117EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1118 EGLConfig config, int hwcFormat,
1119 Protection protection) {
1120 EGLConfig placeholderConfig = config;
1121 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1122 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1123 }
1124 std::vector<EGLint> attributes;
1125 attributes.reserve(7);
1126 attributes.push_back(EGL_WIDTH);
1127 attributes.push_back(1);
1128 attributes.push_back(EGL_HEIGHT);
1129 attributes.push_back(1);
1130 if (protection == Protection::PROTECTED) {
1131 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1132 attributes.push_back(EGL_TRUE);
1133 }
1134 attributes.push_back(EGL_NONE);
1135
1136 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1137}
1138
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001139void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -07001140
Alec Mourid6f09462020-12-07 11:18:17 -08001141int SkiaGLRenderEngine::getContextPriority() {
1142 int value;
1143 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1144 return value;
1145}
1146
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001147void SkiaGLRenderEngine::dump(std::string& result) {
1148 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1149
1150 StringAppendF(&result, "\n ------------RE-----------------\n");
1151 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1152 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1153 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1154 extensions.getVersion());
1155 StringAppendF(&result, "%s\n", extensions.getExtensions());
1156 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1157 supportsProtectedContent());
1158 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1159
1160 {
1161 std::lock_guard<std::mutex> lock(mRenderingMutex);
1162 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1163 StringAppendF(&result, "Dumping buffer ids...\n");
1164 // TODO(178539829): It would be nice to know which layer these are coming from and what
1165 // the texture sizes are.
1166 for (const auto& [id, unused] : mTextureCache) {
1167 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1168 }
1169 StringAppendF(&result, "\n");
1170 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1171 mProtectedTextureCache.size());
1172 StringAppendF(&result, "Dumping buffer ids...\n");
1173 for (const auto& [id, unused] : mProtectedTextureCache) {
1174 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1175 }
1176 StringAppendF(&result, "\n");
1177 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1178 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1179 StringAppendF(&result, "- inputDataspace: %s\n",
1180 dataspaceDetails(
1181 static_cast<android_dataspace>(linearEffect.inputDataspace))
1182 .c_str());
1183 StringAppendF(&result, "- outputDataspace: %s\n",
1184 dataspaceDetails(
1185 static_cast<android_dataspace>(linearEffect.outputDataspace))
1186 .c_str());
1187 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1188 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1189 }
1190 }
1191 StringAppendF(&result, "\n");
1192}
1193
John Reck67b1e2b2020-08-26 13:17:24 -07001194} // namespace skia
1195} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001196} // namespace android