blob: f504a9a4c7450251f32b56d30bbc2348f42bc28c [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Ana Krulec70d15b1b2020-12-01 10:05:15 -080018#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Alec Mouri4ce5ec02021-01-07 17:33:21 -080022#include "SkiaGLRenderEngine.h"
John Reck67b1e2b2020-08-26 13:17:24 -070023
John Reck67b1e2b2020-08-26 13:17:24 -070024#include <EGL/egl.h>
25#include <EGL/eglext.h>
John Reck67b1e2b2020-08-26 13:17:24 -070026#include <GrContextOptions.h>
John Reck67b1e2b2020-08-26 13:17:24 -070027#include <SkCanvas.h>
Alec Mourib34f0b72020-10-02 13:18:34 -070028#include <SkColorFilter.h>
29#include <SkColorMatrix.h>
Alec Mourib5777452020-09-28 11:32:42 -070030#include <SkColorSpace.h>
John Reck67b1e2b2020-08-26 13:17:24 -070031#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070032#include <SkImageFilters.h>
Alec Mouric0aae732021-01-12 13:32:18 -080033#include <SkRegion.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070034#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070035#include <SkSurface.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080036#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070037#include <gl/GrGLInterface.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080038#include <sync/sync.h>
39#include <ui/BlurRegion.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080040#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080041#include <ui/GraphicBuffer.h>
42#include <utils/Trace.h>
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -050043#include "Cache.h"
Alec Mourib5777452020-09-28 11:32:42 -070044
45#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080046#include <cstdint>
47#include <memory>
48
49#include "../gl/GLExtensions.h"
Alec Mouric0aae732021-01-12 13:32:18 -080050#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080051#include "SkBlendMode.h"
52#include "SkImageInfo.h"
53#include "filters/BlurFilter.h"
54#include "filters/LinearEffect.h"
55#include "log/log_main.h"
56#include "skia/debug/SkiaCapture.h"
57#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070058
John Reck67b1e2b2020-08-26 13:17:24 -070059bool checkGlError(const char* op, int lineNumber);
60
61namespace android {
62namespace renderengine {
63namespace skia {
64
Ana Krulec1d12b3b2021-01-27 16:49:51 -080065using base::StringAppendF;
66
John Reck67b1e2b2020-08-26 13:17:24 -070067static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
68 EGLint wanted, EGLConfig* outConfig) {
69 EGLint numConfigs = -1, n = 0;
70 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
71 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
72 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
73 configs.resize(n);
74
75 if (!configs.empty()) {
76 if (attribute != EGL_NONE) {
77 for (EGLConfig config : configs) {
78 EGLint value = 0;
79 eglGetConfigAttrib(dpy, config, attribute, &value);
80 if (wanted == value) {
81 *outConfig = config;
82 return NO_ERROR;
83 }
84 }
85 } else {
86 // just pick the first one
87 *outConfig = configs[0];
88 return NO_ERROR;
89 }
90 }
91
92 return NAME_NOT_FOUND;
93}
94
95static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
96 EGLConfig* config) {
97 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
98 // it is to be used with WIFI displays
99 status_t err;
100 EGLint wantedAttribute;
101 EGLint wantedAttributeValue;
102
103 std::vector<EGLint> attribs;
104 if (renderableType) {
105 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
106 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
107
108 // Default to 8 bits per channel.
109 const EGLint tmpAttribs[] = {
110 EGL_RENDERABLE_TYPE,
111 renderableType,
112 EGL_RECORDABLE_ANDROID,
113 EGL_TRUE,
114 EGL_SURFACE_TYPE,
115 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
116 EGL_FRAMEBUFFER_TARGET_ANDROID,
117 EGL_TRUE,
118 EGL_RED_SIZE,
119 is1010102 ? 10 : 8,
120 EGL_GREEN_SIZE,
121 is1010102 ? 10 : 8,
122 EGL_BLUE_SIZE,
123 is1010102 ? 10 : 8,
124 EGL_ALPHA_SIZE,
125 is1010102 ? 2 : 8,
126 EGL_NONE,
127 };
128 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
129 std::back_inserter(attribs));
130 wantedAttribute = EGL_NONE;
131 wantedAttributeValue = EGL_NONE;
132 } else {
133 // if no renderable type specified, fallback to a simplified query
134 wantedAttribute = EGL_NATIVE_VISUAL_ID;
135 wantedAttributeValue = format;
136 }
137
138 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
139 config);
140 if (err == NO_ERROR) {
141 EGLint caveat;
142 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
143 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
144 }
145
146 return err;
147}
148
149std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
150 const RenderEngineCreationArgs& args) {
151 // initialize EGL for the default display
152 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
153 if (!eglInitialize(display, nullptr, nullptr)) {
154 LOG_ALWAYS_FATAL("failed to initialize EGL");
155 }
156
Yiwei Zhange2650962020-12-01 23:27:58 +0000157 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700158 if (!eglVersion) {
159 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000160 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700161 }
162
Yiwei Zhange2650962020-12-01 23:27:58 +0000163 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700164 if (!eglExtensions) {
165 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000166 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700167 }
168
169 auto& extensions = gl::GLExtensions::getInstance();
170 extensions.initWithEGLStrings(eglVersion, eglExtensions);
171
172 // The code assumes that ES2 or later is available if this extension is
173 // supported.
174 EGLConfig config = EGL_NO_CONFIG_KHR;
175 if (!extensions.hasNoConfigContext()) {
176 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
177 }
178
John Reck67b1e2b2020-08-26 13:17:24 -0700179 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800180 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700181 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800182 protectedContext =
183 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700184 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
185 }
186
Alec Mourid6f09462020-12-07 11:18:17 -0800187 EGLContext ctxt =
188 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700189
190 // if can't create a GL context, we can only abort.
191 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
192
193 EGLSurface placeholder = EGL_NO_SURFACE;
194 if (!extensions.hasSurfacelessContext()) {
195 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
196 Protection::UNPROTECTED);
197 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
198 }
199 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
200 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
201 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
202 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
203
204 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
205 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
206 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
207 Protection::PROTECTED);
208 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
209 "can't create protected placeholder pbuffer");
210 }
211
212 // initialize the renderer while GL is current
213 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000214 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
215 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700216
217 ALOGI("OpenGL ES informations:");
218 ALOGI("vendor : %s", extensions.getVendor());
219 ALOGI("renderer : %s", extensions.getRenderer());
220 ALOGI("version : %s", extensions.getVersion());
221 ALOGI("extensions: %s", extensions.getExtensions());
222 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
223 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
224
225 return engine;
226}
227
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500228void SkiaGLRenderEngine::primeCache() {
229 Cache::primeShaderCache(this);
230}
231
John Reck67b1e2b2020-08-26 13:17:24 -0700232EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
233 status_t err;
234 EGLConfig config;
235
236 // First try to get an ES3 config
237 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
238 if (err != NO_ERROR) {
239 // If ES3 fails, try to get an ES2 config
240 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
241 if (err != NO_ERROR) {
242 // If ES2 still doesn't work, probably because we're on the emulator.
243 // try a simplified query
244 ALOGW("no suitable EGLConfig found, trying a simpler query");
245 err = selectEGLConfig(display, format, 0, &config);
246 if (err != NO_ERROR) {
247 // this EGL is too lame for android
248 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
249 }
250 }
251 }
252
253 if (logConfig) {
254 // print some debugging info
255 EGLint r, g, b, a;
256 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
257 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
258 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
259 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
260 ALOGI("EGL information:");
261 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
262 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
263 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
264 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
265 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
266 }
267
268 return config;
269}
270
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700271SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000272 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700273 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800274 : SkiaRenderEngine(args.renderEngineType),
275 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700276 mEGLContext(ctxt),
277 mPlaceholderSurface(placeholder),
278 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700279 mProtectedPlaceholderSurface(protectedPlaceholder),
Alec Mouri0d995102021-02-24 16:53:38 -0800280 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700281 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
282 LOG_ALWAYS_FATAL_IF(!glInterface.get());
283
284 GrContextOptions options;
285 options.fPreferExternalImagesOverES3 = true;
286 options.fDisableDistanceFieldPaths = true;
Lucas Dupind508e472020-11-04 04:32:06 +0000287 mGrContext = GrDirectContext::MakeGL(glInterface, options);
288 if (useProtectedContext(true)) {
289 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
290 useProtectedContext(false);
291 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700292
293 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500294 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700295 mBlurFilter = new BlurFilter();
296 }
Alec Mouric0aae732021-01-12 13:32:18 -0800297 mCapture = std::make_unique<SkiaCapture>();
298}
299
300SkiaGLRenderEngine::~SkiaGLRenderEngine() {
301 std::lock_guard<std::mutex> lock(mRenderingMutex);
302 mRuntimeEffects.clear();
303 mProtectedTextureCache.clear();
304 mTextureCache.clear();
305
306 if (mBlurFilter) {
307 delete mBlurFilter;
308 }
309
310 mCapture = nullptr;
311
312 mGrContext->flushAndSubmit(true);
313 mGrContext->abandonContext();
314
315 if (mProtectedGrContext) {
316 mProtectedGrContext->flushAndSubmit(true);
317 mProtectedGrContext->abandonContext();
318 }
319
320 if (mPlaceholderSurface != EGL_NO_SURFACE) {
321 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
322 }
323 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
324 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
325 }
326 if (mEGLContext != EGL_NO_CONTEXT) {
327 eglDestroyContext(mEGLDisplay, mEGLContext);
328 }
329 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
330 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
331 }
332 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
333 eglTerminate(mEGLDisplay);
334 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700335}
336
Lucas Dupind508e472020-11-04 04:32:06 +0000337bool SkiaGLRenderEngine::supportsProtectedContent() const {
338 return mProtectedEGLContext != EGL_NO_CONTEXT;
339}
340
341bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
342 if (useProtectedContext == mInProtectedContext) {
343 return true;
344 }
Alec Mourif6a07812021-02-11 21:07:55 -0800345 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000346 return false;
347 }
348 const EGLSurface surface =
349 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
350 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
351 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800352
Lucas Dupind508e472020-11-04 04:32:06 +0000353 if (success) {
354 mInProtectedContext = useProtectedContext;
355 }
356 return success;
357}
358
John Reck67b1e2b2020-08-26 13:17:24 -0700359base::unique_fd SkiaGLRenderEngine::flush() {
360 ATRACE_CALL();
361 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
362 return base::unique_fd();
363 }
364
365 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
366 if (sync == EGL_NO_SYNC_KHR) {
367 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
368 return base::unique_fd();
369 }
370
371 // native fence fd will not be populated until flush() is done.
372 glFlush();
373
374 // get the fence fd
375 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
376 eglDestroySyncKHR(mEGLDisplay, sync);
377 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
378 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
379 }
380
381 return fenceFd;
382}
383
384bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
385 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
386 !gl::GLExtensions::getInstance().hasWaitSync()) {
387 return false;
388 }
389
390 // release the fd and transfer the ownership to EGLSync
391 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
392 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
393 if (sync == EGL_NO_SYNC_KHR) {
394 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
395 return false;
396 }
397
398 // XXX: The spec draft is inconsistent as to whether this should return an
399 // EGLint or void. Ignore the return value for now, as it's not strictly
400 // needed.
401 eglWaitSyncKHR(mEGLDisplay, sync, 0);
402 EGLint error = eglGetError();
403 eglDestroySyncKHR(mEGLDisplay, sync);
404 if (error != EGL_SUCCESS) {
405 ALOGE("failed to wait for EGL native fence sync: %#x", error);
406 return false;
407 }
408
409 return true;
410}
411
Alec Mouri678245d2020-09-30 16:58:23 -0700412static float toDegrees(uint32_t transform) {
413 switch (transform) {
414 case ui::Transform::ROT_90:
415 return 90.0;
416 case ui::Transform::ROT_180:
417 return 180.0;
418 case ui::Transform::ROT_270:
419 return 270.0;
420 default:
421 return 0.0;
422 }
423}
424
Alec Mourib34f0b72020-10-02 13:18:34 -0700425static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
426 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
427 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
428 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
429 matrix[3][3], 0);
430}
431
Alec Mouri029d1952020-10-12 10:37:08 -0700432static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
433 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
434 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
435
436 // Treat unsupported dataspaces as srgb
437 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
438 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
439 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
440 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
441 }
442
443 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
444 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
445 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
446 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
447 }
448
449 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
450 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
451 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
452 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
453
454 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
455 sourceTransfer != destTransfer;
456}
457
Ana Krulecdfec8f52021-01-13 12:51:47 -0800458void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
459 // Only run this if RE is running on its own thread. This way the access to GL
460 // operations is guaranteed to be happening on the same thread.
461 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
462 return;
463 }
464 ATRACE_CALL();
465
466 std::lock_guard<std::mutex> lock(mRenderingMutex);
467 auto iter = mTextureCache.find(buffer->getId());
468 if (iter != mTextureCache.end()) {
469 ALOGV("Texture already exists in cache.");
470 return;
471 } else {
472 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
473 std::make_shared<AutoBackendTexture::LocalRef>();
474 imageTextureRef->setTexture(
475 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), false));
476 mTextureCache.insert({buffer->getId(), imageTextureRef});
477 }
478}
479
John Reck67b1e2b2020-08-26 13:17:24 -0700480void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800481 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700482 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800483 mTextureCache.erase(bufferId);
484 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700485}
486
Ana Krulec47814212021-01-06 19:00:10 -0800487sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
488 const LayerSettings* layer,
489 const DisplaySettings& display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500490 bool undoPremultipliedAlpha,
491 bool requiresLinearEffect) {
John Reckcdb4ed72021-02-04 13:39:33 -0500492 if (layer->stretchEffect.hasEffect()) {
493 // TODO: Implement
494 }
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500495 if (requiresLinearEffect) {
496 const ui::Dataspace inputDataspace =
497 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
498 const ui::Dataspace outputDataspace =
499 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
500
501 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
502 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800503 .undoPremultipliedAlpha = undoPremultipliedAlpha};
504
505 auto effectIter = mRuntimeEffects.find(effect);
506 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
507 if (effectIter == mRuntimeEffects.end()) {
508 runtimeEffect = buildRuntimeEffect(effect);
509 mRuntimeEffects.insert({effect, runtimeEffect});
510 } else {
511 runtimeEffect = effectIter->second;
512 }
513 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
514 display.maxLuminance,
515 layer->source.buffer.maxMasteringLuminance,
516 layer->source.buffer.maxContentLuminance);
517 }
518 return shader;
519}
520
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500521void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500522 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500523 // Record display settings when capture is running.
524 std::stringstream displaySettings;
525 PrintTo(display, &displaySettings);
526 // Store the DisplaySettings in additional information.
527 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
528 SkData::MakeWithCString(displaySettings.str().c_str()));
529 }
530
531 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
532 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
533 // displays might have different scaling when compared to the physical screen.
534
535 canvas->clipRect(getSkRect(display.physicalDisplay));
536 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
537
538 const auto clipWidth = display.clip.width();
539 const auto clipHeight = display.clip.height();
540 auto rotatedClipWidth = clipWidth;
541 auto rotatedClipHeight = clipHeight;
542 // Scale is contingent on the rotation result.
543 if (display.orientation & ui::Transform::ROT_90) {
544 std::swap(rotatedClipWidth, rotatedClipHeight);
545 }
546 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
547 static_cast<SkScalar>(rotatedClipWidth);
548 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
549 static_cast<SkScalar>(rotatedClipHeight);
550 canvas->scale(scaleX, scaleY);
551
552 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
553 // back so that the top left corner of the clip is at (0, 0).
554 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
555 canvas->rotate(toDegrees(display.orientation));
556 canvas->translate(-clipWidth / 2, -clipHeight / 2);
557 canvas->translate(-display.clip.left, -display.clip.top);
558}
559
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500560class AutoSaveRestore {
561public:
562 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
563 ~AutoSaveRestore() { restore(); }
564 void replace(SkCanvas* canvas) {
565 mCanvas = canvas;
566 mSaveCount = canvas->save();
567 }
568 void restore() {
569 if (mCanvas) {
570 mCanvas->restoreToCount(mSaveCount);
571 mCanvas = nullptr;
572 }
573 }
574
575private:
576 SkCanvas* mCanvas;
577 int mSaveCount;
578};
579
John Reck67b1e2b2020-08-26 13:17:24 -0700580status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
581 const std::vector<const LayerSettings*>& layers,
582 const sp<GraphicBuffer>& buffer,
583 const bool useFramebufferCache,
584 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
585 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800586
John Reck67b1e2b2020-08-26 13:17:24 -0700587 std::lock_guard<std::mutex> lock(mRenderingMutex);
588 if (layers.empty()) {
589 ALOGV("Drawing empty layer stack");
590 return NO_ERROR;
591 }
592
593 if (bufferFence.get() >= 0) {
594 // Duplicate the fence for passing to waitFence.
595 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
596 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
597 ATRACE_NAME("Waiting before draw");
598 sync_wait(bufferFence.get(), -1);
599 }
600 }
601 if (buffer == nullptr) {
602 ALOGE("No output buffer provided. Aborting GPU composition.");
603 return BAD_VALUE;
604 }
605
Lucas Dupind508e472020-11-04 04:32:06 +0000606 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800607 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700608 AHardwareBuffer_Desc bufferDesc;
609 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700610
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800611 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700612 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000613 auto iter = cache.find(buffer->getId());
614 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700615 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800616 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800617 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700618 }
619 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800620
621 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800622 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800623 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
624 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800625 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800626 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700627 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800628 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700629 }
630 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800631
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500632 const ui::Dataspace dstDataspace =
633 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500634 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500635 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700636
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500637 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
638 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800639 ALOGE("Cannot acquire canvas from Skia.");
640 return BAD_VALUE;
641 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500642
643 // Find if any layers have requested blur, we'll use that info to decide when to render to an
644 // offscreen buffer and when to render to the native buffer.
645 sk_sp<SkSurface> activeSurface(dstSurface);
646 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500647 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500648 const LayerSettings* blurCompositionLayer = nullptr;
649 if (mBlurFilter) {
650 bool requiresCompositionLayer = false;
651 for (const auto& layer : layers) {
652 if (layer->backgroundBlurRadius > 0) {
653 // when skbug.com/11208 and b/176903027 are resolved we can add the additional
654 // restriction for layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius
655 requiresCompositionLayer = true;
656 }
657 for (auto region : layer->blurRegions) {
658 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
659 requiresCompositionLayer = true;
660 }
661 }
662 if (requiresCompositionLayer) {
663 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500664 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500665 blurCompositionLayer = layer;
666 break;
667 }
668 }
669 }
670
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500671 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700672 // Clear the entire canvas with a transparent black to prevent ghost images.
673 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500674 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800675
676 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
677 // view is still on-screen. The clear region could be re-specified as a black color layer,
678 // however.
679 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500680 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800681 size_t numRects = 0;
682 Rect const* rects = display.clearRegion.getArray(&numRects);
683 SkIRect skRects[numRects];
684 for (int i = 0; i < numRects; ++i) {
685 skRects[i] =
686 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
687 }
688 SkRegion clearRegion;
689 SkPaint paint;
690 sk_sp<SkShader> shader =
691 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500692 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800693 paint.setShader(shader);
694 clearRegion.setRects(skRects, numRects);
695 canvas->drawRegion(clearRegion, paint);
696 }
697
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500698 // setup color filter if necessary
699 sk_sp<SkColorFilter> displayColorTransform;
700 if (display.colorTransform != mat4()) {
701 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
702 }
703
John Reck67b1e2b2020-08-26 13:17:24 -0700704 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500705 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100706
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500707 sk_sp<SkImage> blurInput;
708 if (blurCompositionLayer == layer) {
709 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
710 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
711
712 // save a snapshot of the activeSurface to use as input to the blur shaders
713 blurInput = activeSurface->makeImageSnapshot();
714
715 // TODO we could skip this step if we know the blur will cover the entire image
716 // blit the offscreen framebuffer into the destination AHB
717 SkPaint paint;
718 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500719 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
720 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
721 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
722 String8::format("SurfaceID|%" PRId64, id).c_str(),
723 nullptr);
724 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
725 } else {
726 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
727 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500728
729 // assign dstCanvas to canvas and ensure that the canvas state is up to date
730 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500731 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500732 initCanvas(canvas, display);
733
734 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
735 dstSurface->getCanvas()->getSaveCount());
736 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
737 dstSurface->getCanvas()->getTotalMatrix());
738
739 // assign dstSurface to activeSurface
740 activeSurface = dstSurface;
741 }
742
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500743 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500744 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800745 // Record the name of the layer if the capture is running.
746 std::stringstream layerSettings;
747 PrintTo(*layer, &layerSettings);
748 // Store the LayerSettings in additional information.
749 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
750 SkData::MakeWithCString(layerSettings.str().c_str()));
751 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100752 // Layers have a local transform that should be applied to them
753 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100754
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500755 const auto bounds = getSkRect(layer->geometry.boundaries);
756 if (mBlurFilter && layerHasBlur(layer)) {
757 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
758
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500759 // if multiple layers have blur, then we need to take a snapshot now because
760 // only the lowest layer will have blurImage populated earlier
761 if (!blurInput) {
762 blurInput = activeSurface->makeImageSnapshot();
763 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500764 // rect to be blurred in the coordinate space of blurInput
765 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
766
Lucas Dupinc3800b82020-10-02 16:24:48 -0700767 if (layer->backgroundBlurRadius > 0) {
768 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500769 auto blurredImage =
770 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
771 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100772
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500773 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
774
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500775 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
776 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700777 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500778 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100779 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700780 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500781 cachedBlurs[region.blurRadius] =
782 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
783 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700784 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500785
786 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
787 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700788 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700789 }
790
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500791 // Shadows are assumed to live only on their own layer - it's not valid
792 // to draw the boundary rectangles when there is already a caster shadow
793 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
794 // composition - using a well-defined invalid color is long-term less error-prone.
795 if (layer->shadow.length > 0) {
796 const auto rect = layer->geometry.roundedCornersRadius > 0
797 ? getSkRect(layer->geometry.roundedCornersCrop)
798 : bounds;
799 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
800 continue;
801 }
802
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500803 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
804 (mUseColorManagement &&
805 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
806
807 // quick abort from drawing the remaining portion of the layer
808 if (layer->alpha == 0 && !requiresLinearEffect &&
809 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
810 continue;
811 }
812
813 // If we need to map to linear space or color management is disabled, then mark the source
814 // image with the same colorspace as the destination surface so that Skia's color
815 // management is a no-op.
816 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
817 ? dstDataspace
818 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800819
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500820 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700821 if (layer->source.buffer.buffer) {
822 ATRACE_NAME("DrawImage");
823 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800824 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
825 auto iter = mTextureCache.find(item.buffer->getId());
826 if (iter != mTextureCache.end()) {
827 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700828 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800829 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800830 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800831 item.buffer->toAHardwareBuffer(),
832 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800833 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700834 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800835
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800836 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500837 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800838 item.usePremultipliedAlpha
839 ? kPremul_SkAlphaType
840 : kUnpremul_SkAlphaType,
841 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700842
843 auto texMatrix = getSkM44(item.textureTransform).asM33();
844 // textureTansform was intended to be passed directly into a shader, so when
845 // building the total matrix with the textureTransform we need to first
846 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500847 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800848 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700849
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800850 SkMatrix matrix;
851 if (!texMatrix.invert(&matrix)) {
852 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700853 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800854 // The shader does not respect the translation, so we add it to the texture
855 // transform for the SkImage. This will make sure that the correct layer contents
856 // are drawn in the correct part of the screen.
857 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700858
Ana Krulecb7b28b22020-11-23 14:48:58 -0800859 sk_sp<SkShader> shader;
860
861 if (layer->source.buffer.useTextureFiltering) {
862 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
863 SkSamplingOptions(
864 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
865 &matrix);
866 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500867 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800868 }
Alec Mouri029d1952020-10-12 10:37:08 -0700869
Alec Mouric0aae732021-01-12 13:32:18 -0800870 // Handle opaque images - it's a little nonstandard how we do this.
871 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
872 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
873 // The important language is that when isOpaque is set, opacity is not sampled from the
874 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
875 // here's the conundrum:
876 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
877 // as an internal hint - composition is undefined when there are alpha bits present.
878 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
879 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
880 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
881 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
882 // of a hack anyways.
883 // 3. We can't change the blendmode to src, because while this satisfies the requirement
884 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
885 // because src always clobbers the destination content.
886 //
887 // So, what we do here instead is an additive blend mode where we compose the input
888 // image with a solid black. This might need to be reassess if this does not support
889 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
890 if (item.isOpaque) {
891 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
892 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500893 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800894 }
895
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500896 paint.setShader(createRuntimeEffectShader(shader, layer, display,
897 !item.isOpaque && item.usePremultipliedAlpha,
898 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800899 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700900 } else {
901 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700902 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800903 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
904 .fG = color.g,
905 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800906 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500907 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800908 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500909 /* undoPremultipliedAlpha */ false,
910 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700911 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700912
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500913 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700914
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500915 if (layer->geometry.roundedCornersRadius > 0) {
916 paint.setAntiAlias(true);
917 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800918 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500919 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700920 }
John Reck67b1e2b2020-08-26 13:17:24 -0700921 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500922 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800923 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700924 {
925 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500926 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
927 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700928 }
929
930 if (drawFence != nullptr) {
931 *drawFence = flush();
932 }
933
934 // If flush failed or we don't support native fences, we need to force the
935 // gl command stream to be executed.
936 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
937 if (requireSync) {
938 ATRACE_BEGIN("Submit(sync=true)");
939 } else {
940 ATRACE_BEGIN("Submit(sync=false)");
941 }
Lucas Dupind508e472020-11-04 04:32:06 +0000942 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700943 ATRACE_END();
944 if (!success) {
945 ALOGE("Failed to flush RenderEngine commands");
946 // Chances are, something illegal happened (either the caller passed
947 // us bad parameters, or we messed up our shader generation).
948 return INVALID_OPERATION;
949 }
950
951 // checkErrors();
952 return NO_ERROR;
953}
954
Lucas Dupin3f11e922020-09-22 17:31:04 -0700955inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
956 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
957}
958
959inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
960 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
961}
962
Lucas Dupin21f348e2020-09-16 17:31:26 -0700963inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800964 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700965 const auto cornerRadius = layer->geometry.roundedCornersRadius;
966 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
967}
968
Galia Peycheva80116e52020-11-06 11:57:25 +0100969inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
970 const auto rect = getSkRect(layer->geometry.boundaries);
971 const auto cornersRadius = layer->geometry.roundedCornersRadius;
972 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
973 .cornerRadiusTL = cornersRadius,
974 .cornerRadiusTR = cornersRadius,
975 .cornerRadiusBL = cornersRadius,
976 .cornerRadiusBR = cornersRadius,
977 .alpha = 1,
978 .left = static_cast<int>(rect.fLeft),
979 .top = static_cast<int>(rect.fTop),
980 .right = static_cast<int>(rect.fRight),
981 .bottom = static_cast<int>(rect.fBottom)};
982}
983
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500984inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
985 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
986}
987
Lucas Dupin3f11e922020-09-22 17:31:04 -0700988inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
989 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
990}
991
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700992inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
993 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
994 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
995 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
996 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
997}
998
Lucas Dupin3f11e922020-09-22 17:31:04 -0700999inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1000 return SkPoint3::Make(vector.x, vector.y, vector.z);
1001}
1002
John Reck67b1e2b2020-08-26 13:17:24 -07001003size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1004 return mGrContext->maxTextureSize();
1005}
1006
1007size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1008 return mGrContext->maxRenderTargetSize();
1009}
1010
Lucas Dupin3f11e922020-09-22 17:31:04 -07001011void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1012 const ShadowSettings& settings) {
1013 ATRACE_CALL();
1014 const float casterZ = settings.length / 2.0f;
1015 const auto shadowShape = cornerRadius > 0
1016 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1017 : SkPath::Rect(casterRect);
1018 const auto flags =
1019 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1020
1021 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1022 getSkPoint3(settings.lightPos), settings.lightRadius,
1023 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1024 flags);
1025}
1026
John Reck67b1e2b2020-08-26 13:17:24 -07001027EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001028 EGLContext shareContext,
1029 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001030 Protection protection) {
1031 EGLint renderableType = 0;
1032 if (config == EGL_NO_CONFIG_KHR) {
1033 renderableType = EGL_OPENGL_ES3_BIT;
1034 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1035 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1036 }
1037 EGLint contextClientVersion = 0;
1038 if (renderableType & EGL_OPENGL_ES3_BIT) {
1039 contextClientVersion = 3;
1040 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1041 contextClientVersion = 2;
1042 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1043 contextClientVersion = 1;
1044 } else {
1045 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1046 }
1047
1048 std::vector<EGLint> contextAttributes;
1049 contextAttributes.reserve(7);
1050 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1051 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001052 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001053 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001054 switch (*contextPriority) {
1055 case ContextPriority::REALTIME:
1056 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1057 break;
1058 case ContextPriority::MEDIUM:
1059 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1060 break;
1061 case ContextPriority::LOW:
1062 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1063 break;
1064 case ContextPriority::HIGH:
1065 default:
1066 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1067 break;
1068 }
John Reck67b1e2b2020-08-26 13:17:24 -07001069 }
1070 if (protection == Protection::PROTECTED) {
1071 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1072 contextAttributes.push_back(EGL_TRUE);
1073 }
1074 contextAttributes.push_back(EGL_NONE);
1075
1076 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1077
1078 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1079 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1080 // EGL_NO_CONTEXT so that we can abort.
1081 if (config != EGL_NO_CONFIG_KHR) {
1082 return context;
1083 }
1084 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1085 // should try to fall back to GLES 2.
1086 contextAttributes[1] = 2;
1087 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1088 }
1089
1090 return context;
1091}
1092
Alec Mourid6f09462020-12-07 11:18:17 -08001093std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1094 const RenderEngineCreationArgs& args) {
1095 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1096 return std::nullopt;
1097 }
1098
1099 switch (args.contextPriority) {
1100 case RenderEngine::ContextPriority::REALTIME:
1101 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1102 return RenderEngine::ContextPriority::REALTIME;
1103 } else {
1104 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1105 return RenderEngine::ContextPriority::HIGH;
1106 }
1107 case RenderEngine::ContextPriority::HIGH:
1108 case RenderEngine::ContextPriority::MEDIUM:
1109 case RenderEngine::ContextPriority::LOW:
1110 return args.contextPriority;
1111 default:
1112 return std::nullopt;
1113 }
1114}
1115
John Reck67b1e2b2020-08-26 13:17:24 -07001116EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1117 EGLConfig config, int hwcFormat,
1118 Protection protection) {
1119 EGLConfig placeholderConfig = config;
1120 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1121 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1122 }
1123 std::vector<EGLint> attributes;
1124 attributes.reserve(7);
1125 attributes.push_back(EGL_WIDTH);
1126 attributes.push_back(1);
1127 attributes.push_back(EGL_HEIGHT);
1128 attributes.push_back(1);
1129 if (protection == Protection::PROTECTED) {
1130 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1131 attributes.push_back(EGL_TRUE);
1132 }
1133 attributes.push_back(EGL_NONE);
1134
1135 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1136}
1137
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001138void SkiaGLRenderEngine::cleanFramebufferCache() {}
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