blob: acd3dcfe08c22a96f051109dc3ffd2fdfd559892 [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 Mouri0d995102021-02-24 16:53:38 -0800269 : SkiaRenderEngine(args.renderEngineType),
270 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700271 mEGLContext(ctxt),
272 mPlaceholderSurface(placeholder),
273 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700274 mProtectedPlaceholderSurface(protectedPlaceholder),
Alec Mouri0d995102021-02-24 16:53:38 -0800275 mUseColorManagement(args.useColorManagement) {
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() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100296 cleanFramebufferCache();
Alec Mouric0aae732021-01-12 13:32:18 -0800297
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100298 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800299 if (mBlurFilter) {
300 delete mBlurFilter;
301 }
302
303 mCapture = nullptr;
304
305 mGrContext->flushAndSubmit(true);
306 mGrContext->abandonContext();
307
308 if (mProtectedGrContext) {
309 mProtectedGrContext->flushAndSubmit(true);
310 mProtectedGrContext->abandonContext();
311 }
312
313 if (mPlaceholderSurface != EGL_NO_SURFACE) {
314 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
315 }
316 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
317 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
318 }
319 if (mEGLContext != EGL_NO_CONTEXT) {
320 eglDestroyContext(mEGLDisplay, mEGLContext);
321 }
322 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
323 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
324 }
325 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
326 eglTerminate(mEGLDisplay);
327 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700328}
329
Lucas Dupind508e472020-11-04 04:32:06 +0000330bool SkiaGLRenderEngine::supportsProtectedContent() const {
331 return mProtectedEGLContext != EGL_NO_CONTEXT;
332}
333
334bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
335 if (useProtectedContext == mInProtectedContext) {
336 return true;
337 }
Alec Mourif6a07812021-02-11 21:07:55 -0800338 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000339 return false;
340 }
341 const EGLSurface surface =
342 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
343 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
344 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800345
Lucas Dupind508e472020-11-04 04:32:06 +0000346 if (success) {
347 mInProtectedContext = useProtectedContext;
348 }
349 return success;
350}
351
John Reck67b1e2b2020-08-26 13:17:24 -0700352base::unique_fd SkiaGLRenderEngine::flush() {
353 ATRACE_CALL();
354 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
355 return base::unique_fd();
356 }
357
358 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
359 if (sync == EGL_NO_SYNC_KHR) {
360 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
361 return base::unique_fd();
362 }
363
364 // native fence fd will not be populated until flush() is done.
365 glFlush();
366
367 // get the fence fd
368 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
369 eglDestroySyncKHR(mEGLDisplay, sync);
370 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
371 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
372 }
373
374 return fenceFd;
375}
376
377bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
378 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
379 !gl::GLExtensions::getInstance().hasWaitSync()) {
380 return false;
381 }
382
383 // release the fd and transfer the ownership to EGLSync
384 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
385 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
386 if (sync == EGL_NO_SYNC_KHR) {
387 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
388 return false;
389 }
390
391 // XXX: The spec draft is inconsistent as to whether this should return an
392 // EGLint or void. Ignore the return value for now, as it's not strictly
393 // needed.
394 eglWaitSyncKHR(mEGLDisplay, sync, 0);
395 EGLint error = eglGetError();
396 eglDestroySyncKHR(mEGLDisplay, sync);
397 if (error != EGL_SUCCESS) {
398 ALOGE("failed to wait for EGL native fence sync: %#x", error);
399 return false;
400 }
401
402 return true;
403}
404
Alec Mouri678245d2020-09-30 16:58:23 -0700405static float toDegrees(uint32_t transform) {
406 switch (transform) {
407 case ui::Transform::ROT_90:
408 return 90.0;
409 case ui::Transform::ROT_180:
410 return 180.0;
411 case ui::Transform::ROT_270:
412 return 270.0;
413 default:
414 return 0.0;
415 }
416}
417
Alec Mourib34f0b72020-10-02 13:18:34 -0700418static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
419 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
420 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
421 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
422 matrix[3][3], 0);
423}
424
Alec Mouri029d1952020-10-12 10:37:08 -0700425static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
426 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
427 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
428
429 // Treat unsupported dataspaces as srgb
430 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
431 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
432 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
433 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
434 }
435
436 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
437 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
438 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
439 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
440 }
441
442 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
443 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
444 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
445 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
446
447 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
448 sourceTransfer != destTransfer;
449}
450
Ana Krulecdfec8f52021-01-13 12:51:47 -0800451void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
452 // Only run this if RE is running on its own thread. This way the access to GL
453 // operations is guaranteed to be happening on the same thread.
454 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
455 return;
456 }
457 ATRACE_CALL();
458
459 std::lock_guard<std::mutex> lock(mRenderingMutex);
460 auto iter = mTextureCache.find(buffer->getId());
461 if (iter != mTextureCache.end()) {
462 ALOGV("Texture already exists in cache.");
463 return;
464 } else {
465 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
466 std::make_shared<AutoBackendTexture::LocalRef>();
467 imageTextureRef->setTexture(
468 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), false));
469 mTextureCache.insert({buffer->getId(), imageTextureRef});
470 }
471}
472
John Reck67b1e2b2020-08-26 13:17:24 -0700473void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800474 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700475 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800476 mTextureCache.erase(bufferId);
477 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700478}
479
Ana Krulec47814212021-01-06 19:00:10 -0800480sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
481 const LayerSettings* layer,
482 const DisplaySettings& display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500483 bool undoPremultipliedAlpha,
484 bool requiresLinearEffect) {
John Reckcdb4ed72021-02-04 13:39:33 -0500485 if (layer->stretchEffect.hasEffect()) {
486 // TODO: Implement
487 }
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500488 if (requiresLinearEffect) {
489 const ui::Dataspace inputDataspace =
490 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
491 const ui::Dataspace outputDataspace =
492 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
493
494 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
495 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800496 .undoPremultipliedAlpha = undoPremultipliedAlpha};
497
498 auto effectIter = mRuntimeEffects.find(effect);
499 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
500 if (effectIter == mRuntimeEffects.end()) {
501 runtimeEffect = buildRuntimeEffect(effect);
502 mRuntimeEffects.insert({effect, runtimeEffect});
503 } else {
504 runtimeEffect = effectIter->second;
505 }
506 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
507 display.maxLuminance,
508 layer->source.buffer.maxMasteringLuminance,
509 layer->source.buffer.maxContentLuminance);
510 }
511 return shader;
512}
513
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500514void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500515 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500516 // Record display settings when capture is running.
517 std::stringstream displaySettings;
518 PrintTo(display, &displaySettings);
519 // Store the DisplaySettings in additional information.
520 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
521 SkData::MakeWithCString(displaySettings.str().c_str()));
522 }
523
524 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
525 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
526 // displays might have different scaling when compared to the physical screen.
527
528 canvas->clipRect(getSkRect(display.physicalDisplay));
529 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
530
531 const auto clipWidth = display.clip.width();
532 const auto clipHeight = display.clip.height();
533 auto rotatedClipWidth = clipWidth;
534 auto rotatedClipHeight = clipHeight;
535 // Scale is contingent on the rotation result.
536 if (display.orientation & ui::Transform::ROT_90) {
537 std::swap(rotatedClipWidth, rotatedClipHeight);
538 }
539 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
540 static_cast<SkScalar>(rotatedClipWidth);
541 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
542 static_cast<SkScalar>(rotatedClipHeight);
543 canvas->scale(scaleX, scaleY);
544
545 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
546 // back so that the top left corner of the clip is at (0, 0).
547 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
548 canvas->rotate(toDegrees(display.orientation));
549 canvas->translate(-clipWidth / 2, -clipHeight / 2);
550 canvas->translate(-display.clip.left, -display.clip.top);
551}
552
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500553class AutoSaveRestore {
554public:
555 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
556 ~AutoSaveRestore() { restore(); }
557 void replace(SkCanvas* canvas) {
558 mCanvas = canvas;
559 mSaveCount = canvas->save();
560 }
561 void restore() {
562 if (mCanvas) {
563 mCanvas->restoreToCount(mSaveCount);
564 mCanvas = nullptr;
565 }
566 }
567
568private:
569 SkCanvas* mCanvas;
570 int mSaveCount;
571};
572
John Reck67b1e2b2020-08-26 13:17:24 -0700573status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
574 const std::vector<const LayerSettings*>& layers,
575 const sp<GraphicBuffer>& buffer,
576 const bool useFramebufferCache,
577 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
578 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800579
John Reck67b1e2b2020-08-26 13:17:24 -0700580 std::lock_guard<std::mutex> lock(mRenderingMutex);
581 if (layers.empty()) {
582 ALOGV("Drawing empty layer stack");
583 return NO_ERROR;
584 }
585
586 if (bufferFence.get() >= 0) {
587 // Duplicate the fence for passing to waitFence.
588 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
589 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
590 ATRACE_NAME("Waiting before draw");
591 sync_wait(bufferFence.get(), -1);
592 }
593 }
594 if (buffer == nullptr) {
595 ALOGE("No output buffer provided. Aborting GPU composition.");
596 return BAD_VALUE;
597 }
598
Lucas Dupind508e472020-11-04 04:32:06 +0000599 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800600 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700601 AHardwareBuffer_Desc bufferDesc;
602 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700603
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800604 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700605 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000606 auto iter = cache.find(buffer->getId());
607 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700608 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800609 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800610 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700611 }
612 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800613
614 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800615 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800616 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
617 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800618 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800619 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700620 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800621 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700622 }
623 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800624
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500625 const ui::Dataspace dstDataspace =
626 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500627 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500628 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700629
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500630 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
631 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800632 ALOGE("Cannot acquire canvas from Skia.");
633 return BAD_VALUE;
634 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500635
636 // Find if any layers have requested blur, we'll use that info to decide when to render to an
637 // offscreen buffer and when to render to the native buffer.
638 sk_sp<SkSurface> activeSurface(dstSurface);
639 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500640 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500641 const LayerSettings* blurCompositionLayer = nullptr;
642 if (mBlurFilter) {
643 bool requiresCompositionLayer = false;
644 for (const auto& layer : layers) {
645 if (layer->backgroundBlurRadius > 0) {
646 // when skbug.com/11208 and b/176903027 are resolved we can add the additional
647 // restriction for layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius
648 requiresCompositionLayer = true;
649 }
650 for (auto region : layer->blurRegions) {
651 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
652 requiresCompositionLayer = true;
653 }
654 }
655 if (requiresCompositionLayer) {
656 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500657 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500658 blurCompositionLayer = layer;
659 break;
660 }
661 }
662 }
663
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500664 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700665 // Clear the entire canvas with a transparent black to prevent ghost images.
666 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500667 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800668
669 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
670 // view is still on-screen. The clear region could be re-specified as a black color layer,
671 // however.
672 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500673 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800674 size_t numRects = 0;
675 Rect const* rects = display.clearRegion.getArray(&numRects);
676 SkIRect skRects[numRects];
677 for (int i = 0; i < numRects; ++i) {
678 skRects[i] =
679 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
680 }
681 SkRegion clearRegion;
682 SkPaint paint;
683 sk_sp<SkShader> shader =
684 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500685 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800686 paint.setShader(shader);
687 clearRegion.setRects(skRects, numRects);
688 canvas->drawRegion(clearRegion, paint);
689 }
690
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500691 // setup color filter if necessary
692 sk_sp<SkColorFilter> displayColorTransform;
693 if (display.colorTransform != mat4()) {
694 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
695 }
696
John Reck67b1e2b2020-08-26 13:17:24 -0700697 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500698 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100699
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500700 sk_sp<SkImage> blurInput;
701 if (blurCompositionLayer == layer) {
702 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
703 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
704
705 // save a snapshot of the activeSurface to use as input to the blur shaders
706 blurInput = activeSurface->makeImageSnapshot();
707
708 // TODO we could skip this step if we know the blur will cover the entire image
709 // blit the offscreen framebuffer into the destination AHB
710 SkPaint paint;
711 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500712 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
713 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
714 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
715 String8::format("SurfaceID|%" PRId64, id).c_str(),
716 nullptr);
717 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
718 } else {
719 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
720 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500721
722 // assign dstCanvas to canvas and ensure that the canvas state is up to date
723 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500724 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500725 initCanvas(canvas, display);
726
727 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
728 dstSurface->getCanvas()->getSaveCount());
729 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
730 dstSurface->getCanvas()->getTotalMatrix());
731
732 // assign dstSurface to activeSurface
733 activeSurface = dstSurface;
734 }
735
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500736 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500737 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800738 // Record the name of the layer if the capture is running.
739 std::stringstream layerSettings;
740 PrintTo(*layer, &layerSettings);
741 // Store the LayerSettings in additional information.
742 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
743 SkData::MakeWithCString(layerSettings.str().c_str()));
744 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100745 // Layers have a local transform that should be applied to them
746 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100747
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500748 const auto bounds = getSkRect(layer->geometry.boundaries);
749 if (mBlurFilter && layerHasBlur(layer)) {
750 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
751
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500752 // if multiple layers have blur, then we need to take a snapshot now because
753 // only the lowest layer will have blurImage populated earlier
754 if (!blurInput) {
755 blurInput = activeSurface->makeImageSnapshot();
756 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500757 // rect to be blurred in the coordinate space of blurInput
758 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
759
Lucas Dupinc3800b82020-10-02 16:24:48 -0700760 if (layer->backgroundBlurRadius > 0) {
761 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500762 auto blurredImage =
763 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
764 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100765
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500766 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
767
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500768 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
769 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700770 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500771 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100772 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700773 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500774 cachedBlurs[region.blurRadius] =
775 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
776 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700777 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500778
779 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
780 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700781 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700782 }
783
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500784 // Shadows are assumed to live only on their own layer - it's not valid
785 // to draw the boundary rectangles when there is already a caster shadow
786 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
787 // composition - using a well-defined invalid color is long-term less error-prone.
788 if (layer->shadow.length > 0) {
789 const auto rect = layer->geometry.roundedCornersRadius > 0
790 ? getSkRect(layer->geometry.roundedCornersCrop)
791 : bounds;
792 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
793 continue;
794 }
795
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500796 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
797 (mUseColorManagement &&
798 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
799
800 // quick abort from drawing the remaining portion of the layer
801 if (layer->alpha == 0 && !requiresLinearEffect &&
802 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
803 continue;
804 }
805
806 // If we need to map to linear space or color management is disabled, then mark the source
807 // image with the same colorspace as the destination surface so that Skia's color
808 // management is a no-op.
809 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
810 ? dstDataspace
811 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800812
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500813 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700814 if (layer->source.buffer.buffer) {
815 ATRACE_NAME("DrawImage");
816 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800817 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
818 auto iter = mTextureCache.find(item.buffer->getId());
819 if (iter != mTextureCache.end()) {
820 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700821 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800822 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800823 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800824 item.buffer->toAHardwareBuffer(),
825 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800826 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700827 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800828
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800829 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500830 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800831 item.usePremultipliedAlpha
832 ? kPremul_SkAlphaType
833 : kUnpremul_SkAlphaType,
834 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700835
836 auto texMatrix = getSkM44(item.textureTransform).asM33();
837 // textureTansform was intended to be passed directly into a shader, so when
838 // building the total matrix with the textureTransform we need to first
839 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500840 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800841 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700842
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800843 SkMatrix matrix;
844 if (!texMatrix.invert(&matrix)) {
845 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700846 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800847 // The shader does not respect the translation, so we add it to the texture
848 // transform for the SkImage. This will make sure that the correct layer contents
849 // are drawn in the correct part of the screen.
850 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700851
Ana Krulecb7b28b22020-11-23 14:48:58 -0800852 sk_sp<SkShader> shader;
853
854 if (layer->source.buffer.useTextureFiltering) {
855 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
856 SkSamplingOptions(
857 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
858 &matrix);
859 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500860 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800861 }
Alec Mouri029d1952020-10-12 10:37:08 -0700862
Alec Mouric0aae732021-01-12 13:32:18 -0800863 // Handle opaque images - it's a little nonstandard how we do this.
864 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
865 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
866 // The important language is that when isOpaque is set, opacity is not sampled from the
867 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
868 // here's the conundrum:
869 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
870 // as an internal hint - composition is undefined when there are alpha bits present.
871 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
872 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
873 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
874 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
875 // of a hack anyways.
876 // 3. We can't change the blendmode to src, because while this satisfies the requirement
877 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
878 // because src always clobbers the destination content.
879 //
880 // So, what we do here instead is an additive blend mode where we compose the input
881 // image with a solid black. This might need to be reassess if this does not support
882 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
883 if (item.isOpaque) {
884 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
885 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500886 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800887 }
888
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500889 paint.setShader(createRuntimeEffectShader(shader, layer, display,
890 !item.isOpaque && item.usePremultipliedAlpha,
891 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800892 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700893 } else {
894 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700895 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800896 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
897 .fG = color.g,
898 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800899 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500900 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800901 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500902 /* undoPremultipliedAlpha */ false,
903 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700904 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700905
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500906 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700907
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500908 if (layer->geometry.roundedCornersRadius > 0) {
909 paint.setAntiAlias(true);
910 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800911 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500912 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700913 }
John Reck67b1e2b2020-08-26 13:17:24 -0700914 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500915 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800916 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700917 {
918 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500919 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
920 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700921 }
922
923 if (drawFence != nullptr) {
924 *drawFence = flush();
925 }
926
927 // If flush failed or we don't support native fences, we need to force the
928 // gl command stream to be executed.
929 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
930 if (requireSync) {
931 ATRACE_BEGIN("Submit(sync=true)");
932 } else {
933 ATRACE_BEGIN("Submit(sync=false)");
934 }
Lucas Dupind508e472020-11-04 04:32:06 +0000935 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700936 ATRACE_END();
937 if (!success) {
938 ALOGE("Failed to flush RenderEngine commands");
939 // Chances are, something illegal happened (either the caller passed
940 // us bad parameters, or we messed up our shader generation).
941 return INVALID_OPERATION;
942 }
943
944 // checkErrors();
945 return NO_ERROR;
946}
947
Lucas Dupin3f11e922020-09-22 17:31:04 -0700948inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
949 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
950}
951
952inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
953 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
954}
955
Lucas Dupin21f348e2020-09-16 17:31:26 -0700956inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800957 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700958 const auto cornerRadius = layer->geometry.roundedCornersRadius;
959 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
960}
961
Galia Peycheva80116e52020-11-06 11:57:25 +0100962inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
963 const auto rect = getSkRect(layer->geometry.boundaries);
964 const auto cornersRadius = layer->geometry.roundedCornersRadius;
965 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
966 .cornerRadiusTL = cornersRadius,
967 .cornerRadiusTR = cornersRadius,
968 .cornerRadiusBL = cornersRadius,
969 .cornerRadiusBR = cornersRadius,
970 .alpha = 1,
971 .left = static_cast<int>(rect.fLeft),
972 .top = static_cast<int>(rect.fTop),
973 .right = static_cast<int>(rect.fRight),
974 .bottom = static_cast<int>(rect.fBottom)};
975}
976
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500977inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
978 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
979}
980
Lucas Dupin3f11e922020-09-22 17:31:04 -0700981inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
982 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
983}
984
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700985inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
986 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
987 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
988 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
989 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
990}
991
Lucas Dupin3f11e922020-09-22 17:31:04 -0700992inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
993 return SkPoint3::Make(vector.x, vector.y, vector.z);
994}
995
John Reck67b1e2b2020-08-26 13:17:24 -0700996size_t SkiaGLRenderEngine::getMaxTextureSize() const {
997 return mGrContext->maxTextureSize();
998}
999
1000size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1001 return mGrContext->maxRenderTargetSize();
1002}
1003
Lucas Dupin3f11e922020-09-22 17:31:04 -07001004void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1005 const ShadowSettings& settings) {
1006 ATRACE_CALL();
1007 const float casterZ = settings.length / 2.0f;
1008 const auto shadowShape = cornerRadius > 0
1009 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1010 : SkPath::Rect(casterRect);
1011 const auto flags =
1012 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1013
1014 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1015 getSkPoint3(settings.lightPos), settings.lightRadius,
1016 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1017 flags);
1018}
1019
John Reck67b1e2b2020-08-26 13:17:24 -07001020EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001021 EGLContext shareContext,
1022 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001023 Protection protection) {
1024 EGLint renderableType = 0;
1025 if (config == EGL_NO_CONFIG_KHR) {
1026 renderableType = EGL_OPENGL_ES3_BIT;
1027 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1028 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1029 }
1030 EGLint contextClientVersion = 0;
1031 if (renderableType & EGL_OPENGL_ES3_BIT) {
1032 contextClientVersion = 3;
1033 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1034 contextClientVersion = 2;
1035 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1036 contextClientVersion = 1;
1037 } else {
1038 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1039 }
1040
1041 std::vector<EGLint> contextAttributes;
1042 contextAttributes.reserve(7);
1043 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1044 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001045 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001046 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001047 switch (*contextPriority) {
1048 case ContextPriority::REALTIME:
1049 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1050 break;
1051 case ContextPriority::MEDIUM:
1052 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1053 break;
1054 case ContextPriority::LOW:
1055 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1056 break;
1057 case ContextPriority::HIGH:
1058 default:
1059 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1060 break;
1061 }
John Reck67b1e2b2020-08-26 13:17:24 -07001062 }
1063 if (protection == Protection::PROTECTED) {
1064 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1065 contextAttributes.push_back(EGL_TRUE);
1066 }
1067 contextAttributes.push_back(EGL_NONE);
1068
1069 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1070
1071 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1072 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1073 // EGL_NO_CONTEXT so that we can abort.
1074 if (config != EGL_NO_CONFIG_KHR) {
1075 return context;
1076 }
1077 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1078 // should try to fall back to GLES 2.
1079 contextAttributes[1] = 2;
1080 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1081 }
1082
1083 return context;
1084}
1085
Alec Mourid6f09462020-12-07 11:18:17 -08001086std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1087 const RenderEngineCreationArgs& args) {
1088 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1089 return std::nullopt;
1090 }
1091
1092 switch (args.contextPriority) {
1093 case RenderEngine::ContextPriority::REALTIME:
1094 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1095 return RenderEngine::ContextPriority::REALTIME;
1096 } else {
1097 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1098 return RenderEngine::ContextPriority::HIGH;
1099 }
1100 case RenderEngine::ContextPriority::HIGH:
1101 case RenderEngine::ContextPriority::MEDIUM:
1102 case RenderEngine::ContextPriority::LOW:
1103 return args.contextPriority;
1104 default:
1105 return std::nullopt;
1106 }
1107}
1108
John Reck67b1e2b2020-08-26 13:17:24 -07001109EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1110 EGLConfig config, int hwcFormat,
1111 Protection protection) {
1112 EGLConfig placeholderConfig = config;
1113 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1114 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1115 }
1116 std::vector<EGLint> attributes;
1117 attributes.reserve(7);
1118 attributes.push_back(EGL_WIDTH);
1119 attributes.push_back(1);
1120 attributes.push_back(EGL_HEIGHT);
1121 attributes.push_back(1);
1122 if (protection == Protection::PROTECTED) {
1123 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1124 attributes.push_back(EGL_TRUE);
1125 }
1126 attributes.push_back(EGL_NONE);
1127
1128 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1129}
1130
Marin Shalamanovcea12ef2021-03-15 17:00:51 +01001131void SkiaGLRenderEngine::cleanFramebufferCache() {
1132 // TODO(b/180767535) Remove this method and use b/180767535 instead, which would allow
1133 // SF to control texture lifecycle more tightly rather than through custom hooks into RE.
1134 std::lock_guard<std::mutex> lock(mRenderingMutex);
1135 mRuntimeEffects.clear();
1136 mProtectedTextureCache.clear();
1137 mTextureCache.clear();
1138}
John Reck67b1e2b2020-08-26 13:17:24 -07001139
Alec Mourid6f09462020-12-07 11:18:17 -08001140int SkiaGLRenderEngine::getContextPriority() {
1141 int value;
1142 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1143 return value;
1144}
1145
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001146void SkiaGLRenderEngine::dump(std::string& result) {
1147 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1148
1149 StringAppendF(&result, "\n ------------RE-----------------\n");
1150 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1151 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1152 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1153 extensions.getVersion());
1154 StringAppendF(&result, "%s\n", extensions.getExtensions());
1155 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1156 supportsProtectedContent());
1157 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1158
1159 {
1160 std::lock_guard<std::mutex> lock(mRenderingMutex);
1161 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1162 StringAppendF(&result, "Dumping buffer ids...\n");
1163 // TODO(178539829): It would be nice to know which layer these are coming from and what
1164 // the texture sizes are.
1165 for (const auto& [id, unused] : mTextureCache) {
1166 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1167 }
1168 StringAppendF(&result, "\n");
1169 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1170 mProtectedTextureCache.size());
1171 StringAppendF(&result, "Dumping buffer ids...\n");
1172 for (const auto& [id, unused] : mProtectedTextureCache) {
1173 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1174 }
1175 StringAppendF(&result, "\n");
1176 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1177 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1178 StringAppendF(&result, "- inputDataspace: %s\n",
1179 dataspaceDetails(
1180 static_cast<android_dataspace>(linearEffect.inputDataspace))
1181 .c_str());
1182 StringAppendF(&result, "- outputDataspace: %s\n",
1183 dataspaceDetails(
1184 static_cast<android_dataspace>(linearEffect.outputDataspace))
1185 .c_str());
1186 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1187 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1188 }
1189 }
1190 StringAppendF(&result, "\n");
1191}
1192
John Reck67b1e2b2020-08-26 13:17:24 -07001193} // namespace skia
1194} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001195} // namespace android