blob: e55f55bc5f3a4b2f85fcb58d1c62f60f540d8c79 [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
Ady Abraham193426d2021-02-18 14:01:53 -0800606 validateOutputBufferUsage(buffer);
607
Lucas Dupind508e472020-11-04 04:32:06 +0000608 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800609 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700610 AHardwareBuffer_Desc bufferDesc;
611 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700612
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800613 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700614 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000615 auto iter = cache.find(buffer->getId());
616 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700617 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800618 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800619 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700620 }
621 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800622
623 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800624 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800625 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
626 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800627 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800628 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700629 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800630 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700631 }
632 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800633
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500634 const ui::Dataspace dstDataspace =
635 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500636 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500637 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700638
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500639 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
640 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800641 ALOGE("Cannot acquire canvas from Skia.");
642 return BAD_VALUE;
643 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500644
645 // Find if any layers have requested blur, we'll use that info to decide when to render to an
646 // offscreen buffer and when to render to the native buffer.
647 sk_sp<SkSurface> activeSurface(dstSurface);
648 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500649 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500650 const LayerSettings* blurCompositionLayer = nullptr;
651 if (mBlurFilter) {
652 bool requiresCompositionLayer = false;
653 for (const auto& layer : layers) {
654 if (layer->backgroundBlurRadius > 0) {
655 // when skbug.com/11208 and b/176903027 are resolved we can add the additional
656 // restriction for layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius
657 requiresCompositionLayer = true;
658 }
659 for (auto region : layer->blurRegions) {
660 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
661 requiresCompositionLayer = true;
662 }
663 }
664 if (requiresCompositionLayer) {
665 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500666 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500667 blurCompositionLayer = layer;
668 break;
669 }
670 }
671 }
672
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500673 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700674 // Clear the entire canvas with a transparent black to prevent ghost images.
675 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500676 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800677
678 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
679 // view is still on-screen. The clear region could be re-specified as a black color layer,
680 // however.
681 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500682 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800683 size_t numRects = 0;
684 Rect const* rects = display.clearRegion.getArray(&numRects);
685 SkIRect skRects[numRects];
686 for (int i = 0; i < numRects; ++i) {
687 skRects[i] =
688 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
689 }
690 SkRegion clearRegion;
691 SkPaint paint;
692 sk_sp<SkShader> shader =
693 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500694 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800695 paint.setShader(shader);
696 clearRegion.setRects(skRects, numRects);
697 canvas->drawRegion(clearRegion, paint);
698 }
699
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500700 // setup color filter if necessary
701 sk_sp<SkColorFilter> displayColorTransform;
702 if (display.colorTransform != mat4()) {
703 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
704 }
705
John Reck67b1e2b2020-08-26 13:17:24 -0700706 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500707 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100708
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500709 sk_sp<SkImage> blurInput;
710 if (blurCompositionLayer == layer) {
711 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
712 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
713
714 // save a snapshot of the activeSurface to use as input to the blur shaders
715 blurInput = activeSurface->makeImageSnapshot();
716
717 // TODO we could skip this step if we know the blur will cover the entire image
718 // blit the offscreen framebuffer into the destination AHB
719 SkPaint paint;
720 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500721 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
722 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
723 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
724 String8::format("SurfaceID|%" PRId64, id).c_str(),
725 nullptr);
726 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
727 } else {
728 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
729 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500730
731 // assign dstCanvas to canvas and ensure that the canvas state is up to date
732 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500733 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500734 initCanvas(canvas, display);
735
736 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
737 dstSurface->getCanvas()->getSaveCount());
738 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
739 dstSurface->getCanvas()->getTotalMatrix());
740
741 // assign dstSurface to activeSurface
742 activeSurface = dstSurface;
743 }
744
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500745 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500746 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800747 // Record the name of the layer if the capture is running.
748 std::stringstream layerSettings;
749 PrintTo(*layer, &layerSettings);
750 // Store the LayerSettings in additional information.
751 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
752 SkData::MakeWithCString(layerSettings.str().c_str()));
753 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100754 // Layers have a local transform that should be applied to them
755 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100756
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500757 const auto bounds = getSkRect(layer->geometry.boundaries);
758 if (mBlurFilter && layerHasBlur(layer)) {
759 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
760
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500761 // if multiple layers have blur, then we need to take a snapshot now because
762 // only the lowest layer will have blurImage populated earlier
763 if (!blurInput) {
764 blurInput = activeSurface->makeImageSnapshot();
765 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500766 // rect to be blurred in the coordinate space of blurInput
767 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
768
Galia Peychevae425ac82021-03-15 17:12:03 +0100769 // TODO(b/182216890): Filter out empty layers earlier
770 if (blurRect.width() > 0 && blurRect.height() > 0) {
771 if (layer->backgroundBlurRadius > 0) {
772 ATRACE_NAME("BackgroundBlur");
773 auto blurredImage =
774 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
775 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100776
Galia Peychevae425ac82021-03-15 17:12:03 +0100777 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500778
Galia Peychevae425ac82021-03-15 17:12:03 +0100779 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect,
780 blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700781 }
Galia Peychevae425ac82021-03-15 17:12:03 +0100782 for (auto region : layer->blurRegions) {
783 if (cachedBlurs[region.blurRadius] == nullptr) {
784 ATRACE_NAME("BlurRegion");
785 cachedBlurs[region.blurRadius] =
786 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
787 blurRect);
788 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500789
Galia Peychevae425ac82021-03-15 17:12:03 +0100790 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
791 cachedBlurs[region.blurRadius], blurInput);
792 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700793 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700794 }
795
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500796 // Shadows are assumed to live only on their own layer - it's not valid
797 // to draw the boundary rectangles when there is already a caster shadow
798 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
799 // composition - using a well-defined invalid color is long-term less error-prone.
800 if (layer->shadow.length > 0) {
801 const auto rect = layer->geometry.roundedCornersRadius > 0
802 ? getSkRect(layer->geometry.roundedCornersCrop)
803 : bounds;
804 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
805 continue;
806 }
807
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500808 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
809 (mUseColorManagement &&
810 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
811
812 // quick abort from drawing the remaining portion of the layer
813 if (layer->alpha == 0 && !requiresLinearEffect &&
814 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
815 continue;
816 }
817
818 // If we need to map to linear space or color management is disabled, then mark the source
819 // image with the same colorspace as the destination surface so that Skia's color
820 // management is a no-op.
821 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
822 ? dstDataspace
823 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800824
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500825 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700826 if (layer->source.buffer.buffer) {
827 ATRACE_NAME("DrawImage");
Ady Abraham193426d2021-02-18 14:01:53 -0800828 validateInputBufferUsage(layer->source.buffer.buffer);
John Reck67b1e2b2020-08-26 13:17:24 -0700829 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800830 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
831 auto iter = mTextureCache.find(item.buffer->getId());
832 if (iter != mTextureCache.end()) {
833 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700834 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800835 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800836 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800837 item.buffer->toAHardwareBuffer(),
838 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800839 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700840 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800841
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800842 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500843 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800844 item.usePremultipliedAlpha
845 ? kPremul_SkAlphaType
846 : kUnpremul_SkAlphaType,
847 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700848
849 auto texMatrix = getSkM44(item.textureTransform).asM33();
850 // textureTansform was intended to be passed directly into a shader, so when
851 // building the total matrix with the textureTransform we need to first
852 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500853 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800854 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700855
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800856 SkMatrix matrix;
857 if (!texMatrix.invert(&matrix)) {
858 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700859 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800860 // The shader does not respect the translation, so we add it to the texture
861 // transform for the SkImage. This will make sure that the correct layer contents
862 // are drawn in the correct part of the screen.
863 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700864
Ana Krulecb7b28b22020-11-23 14:48:58 -0800865 sk_sp<SkShader> shader;
866
867 if (layer->source.buffer.useTextureFiltering) {
868 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
869 SkSamplingOptions(
870 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
871 &matrix);
872 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500873 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800874 }
Alec Mouri029d1952020-10-12 10:37:08 -0700875
Alec Mouric0aae732021-01-12 13:32:18 -0800876 // Handle opaque images - it's a little nonstandard how we do this.
877 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
878 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
879 // The important language is that when isOpaque is set, opacity is not sampled from the
880 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
881 // here's the conundrum:
882 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
883 // as an internal hint - composition is undefined when there are alpha bits present.
884 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
885 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
886 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
887 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
888 // of a hack anyways.
889 // 3. We can't change the blendmode to src, because while this satisfies the requirement
890 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
891 // because src always clobbers the destination content.
892 //
893 // So, what we do here instead is an additive blend mode where we compose the input
894 // image with a solid black. This might need to be reassess if this does not support
895 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
896 if (item.isOpaque) {
897 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
898 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500899 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800900 }
901
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500902 paint.setShader(createRuntimeEffectShader(shader, layer, display,
903 !item.isOpaque && item.usePremultipliedAlpha,
904 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800905 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700906 } else {
907 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700908 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800909 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
910 .fG = color.g,
911 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800912 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500913 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800914 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500915 /* undoPremultipliedAlpha */ false,
916 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700917 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700918
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500919 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700920
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500921 if (layer->geometry.roundedCornersRadius > 0) {
922 paint.setAntiAlias(true);
923 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800924 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500925 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700926 }
John Reck67b1e2b2020-08-26 13:17:24 -0700927 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500928 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800929 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700930 {
931 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500932 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
933 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700934 }
935
936 if (drawFence != nullptr) {
937 *drawFence = flush();
938 }
939
940 // If flush failed or we don't support native fences, we need to force the
941 // gl command stream to be executed.
942 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
943 if (requireSync) {
944 ATRACE_BEGIN("Submit(sync=true)");
945 } else {
946 ATRACE_BEGIN("Submit(sync=false)");
947 }
Lucas Dupind508e472020-11-04 04:32:06 +0000948 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700949 ATRACE_END();
950 if (!success) {
951 ALOGE("Failed to flush RenderEngine commands");
952 // Chances are, something illegal happened (either the caller passed
953 // us bad parameters, or we messed up our shader generation).
954 return INVALID_OPERATION;
955 }
956
957 // checkErrors();
958 return NO_ERROR;
959}
960
Lucas Dupin3f11e922020-09-22 17:31:04 -0700961inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
962 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
963}
964
965inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
966 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
967}
968
Lucas Dupin21f348e2020-09-16 17:31:26 -0700969inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800970 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700971 const auto cornerRadius = layer->geometry.roundedCornersRadius;
972 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
973}
974
Galia Peycheva80116e52020-11-06 11:57:25 +0100975inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
976 const auto rect = getSkRect(layer->geometry.boundaries);
977 const auto cornersRadius = layer->geometry.roundedCornersRadius;
978 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
979 .cornerRadiusTL = cornersRadius,
980 .cornerRadiusTR = cornersRadius,
981 .cornerRadiusBL = cornersRadius,
982 .cornerRadiusBR = cornersRadius,
983 .alpha = 1,
984 .left = static_cast<int>(rect.fLeft),
985 .top = static_cast<int>(rect.fTop),
986 .right = static_cast<int>(rect.fRight),
987 .bottom = static_cast<int>(rect.fBottom)};
988}
989
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500990inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
991 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
992}
993
Lucas Dupin3f11e922020-09-22 17:31:04 -0700994inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
995 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
996}
997
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700998inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
999 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1000 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1001 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1002 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1003}
1004
Lucas Dupin3f11e922020-09-22 17:31:04 -07001005inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1006 return SkPoint3::Make(vector.x, vector.y, vector.z);
1007}
1008
John Reck67b1e2b2020-08-26 13:17:24 -07001009size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1010 return mGrContext->maxTextureSize();
1011}
1012
1013size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1014 return mGrContext->maxRenderTargetSize();
1015}
1016
Lucas Dupin3f11e922020-09-22 17:31:04 -07001017void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1018 const ShadowSettings& settings) {
1019 ATRACE_CALL();
1020 const float casterZ = settings.length / 2.0f;
1021 const auto shadowShape = cornerRadius > 0
1022 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1023 : SkPath::Rect(casterRect);
1024 const auto flags =
1025 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1026
1027 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1028 getSkPoint3(settings.lightPos), settings.lightRadius,
1029 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1030 flags);
1031}
1032
John Reck67b1e2b2020-08-26 13:17:24 -07001033EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001034 EGLContext shareContext,
1035 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001036 Protection protection) {
1037 EGLint renderableType = 0;
1038 if (config == EGL_NO_CONFIG_KHR) {
1039 renderableType = EGL_OPENGL_ES3_BIT;
1040 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1041 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1042 }
1043 EGLint contextClientVersion = 0;
1044 if (renderableType & EGL_OPENGL_ES3_BIT) {
1045 contextClientVersion = 3;
1046 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1047 contextClientVersion = 2;
1048 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1049 contextClientVersion = 1;
1050 } else {
1051 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1052 }
1053
1054 std::vector<EGLint> contextAttributes;
1055 contextAttributes.reserve(7);
1056 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1057 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001058 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001059 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001060 switch (*contextPriority) {
1061 case ContextPriority::REALTIME:
1062 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1063 break;
1064 case ContextPriority::MEDIUM:
1065 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1066 break;
1067 case ContextPriority::LOW:
1068 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1069 break;
1070 case ContextPriority::HIGH:
1071 default:
1072 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1073 break;
1074 }
John Reck67b1e2b2020-08-26 13:17:24 -07001075 }
1076 if (protection == Protection::PROTECTED) {
1077 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1078 contextAttributes.push_back(EGL_TRUE);
1079 }
1080 contextAttributes.push_back(EGL_NONE);
1081
1082 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1083
1084 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1085 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1086 // EGL_NO_CONTEXT so that we can abort.
1087 if (config != EGL_NO_CONFIG_KHR) {
1088 return context;
1089 }
1090 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1091 // should try to fall back to GLES 2.
1092 contextAttributes[1] = 2;
1093 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1094 }
1095
1096 return context;
1097}
1098
Alec Mourid6f09462020-12-07 11:18:17 -08001099std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1100 const RenderEngineCreationArgs& args) {
1101 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1102 return std::nullopt;
1103 }
1104
1105 switch (args.contextPriority) {
1106 case RenderEngine::ContextPriority::REALTIME:
1107 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1108 return RenderEngine::ContextPriority::REALTIME;
1109 } else {
1110 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1111 return RenderEngine::ContextPriority::HIGH;
1112 }
1113 case RenderEngine::ContextPriority::HIGH:
1114 case RenderEngine::ContextPriority::MEDIUM:
1115 case RenderEngine::ContextPriority::LOW:
1116 return args.contextPriority;
1117 default:
1118 return std::nullopt;
1119 }
1120}
1121
John Reck67b1e2b2020-08-26 13:17:24 -07001122EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1123 EGLConfig config, int hwcFormat,
1124 Protection protection) {
1125 EGLConfig placeholderConfig = config;
1126 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1127 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1128 }
1129 std::vector<EGLint> attributes;
1130 attributes.reserve(7);
1131 attributes.push_back(EGL_WIDTH);
1132 attributes.push_back(1);
1133 attributes.push_back(EGL_HEIGHT);
1134 attributes.push_back(1);
1135 if (protection == Protection::PROTECTED) {
1136 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1137 attributes.push_back(EGL_TRUE);
1138 }
1139 attributes.push_back(EGL_NONE);
1140
1141 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1142}
1143
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001144void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -07001145
Alec Mourid6f09462020-12-07 11:18:17 -08001146int SkiaGLRenderEngine::getContextPriority() {
1147 int value;
1148 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1149 return value;
1150}
1151
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001152void SkiaGLRenderEngine::dump(std::string& result) {
1153 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1154
1155 StringAppendF(&result, "\n ------------RE-----------------\n");
1156 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1157 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1158 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1159 extensions.getVersion());
1160 StringAppendF(&result, "%s\n", extensions.getExtensions());
1161 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1162 supportsProtectedContent());
1163 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1164
1165 {
1166 std::lock_guard<std::mutex> lock(mRenderingMutex);
1167 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1168 StringAppendF(&result, "Dumping buffer ids...\n");
1169 // TODO(178539829): It would be nice to know which layer these are coming from and what
1170 // the texture sizes are.
1171 for (const auto& [id, unused] : mTextureCache) {
1172 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1173 }
1174 StringAppendF(&result, "\n");
1175 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1176 mProtectedTextureCache.size());
1177 StringAppendF(&result, "Dumping buffer ids...\n");
1178 for (const auto& [id, unused] : mProtectedTextureCache) {
1179 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1180 }
1181 StringAppendF(&result, "\n");
1182 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1183 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1184 StringAppendF(&result, "- inputDataspace: %s\n",
1185 dataspaceDetails(
1186 static_cast<android_dataspace>(linearEffect.inputDataspace))
1187 .c_str());
1188 StringAppendF(&result, "- outputDataspace: %s\n",
1189 dataspaceDetails(
1190 static_cast<android_dataspace>(linearEffect.outputDataspace))
1191 .c_str());
1192 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1193 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1194 }
1195 }
1196 StringAppendF(&result, "\n");
1197}
1198
John Reck67b1e2b2020-08-26 13:17:24 -07001199} // namespace skia
1200} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001201} // namespace android