blob: f76bfa2495d5f87dbda255cb11ad0f14c186a0b8 [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) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500654 if (layer->backgroundBlurRadius > 0 &&
655 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500656 requiresCompositionLayer = true;
657 }
658 for (auto region : layer->blurRegions) {
659 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
660 requiresCompositionLayer = true;
661 }
662 }
663 if (requiresCompositionLayer) {
664 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500665 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500666 blurCompositionLayer = layer;
667 break;
668 }
669 }
670 }
671
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500672 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700673 // Clear the entire canvas with a transparent black to prevent ghost images.
674 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500675 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800676
677 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
678 // view is still on-screen. The clear region could be re-specified as a black color layer,
679 // however.
680 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500681 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800682 size_t numRects = 0;
683 Rect const* rects = display.clearRegion.getArray(&numRects);
684 SkIRect skRects[numRects];
685 for (int i = 0; i < numRects; ++i) {
686 skRects[i] =
687 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
688 }
689 SkRegion clearRegion;
690 SkPaint paint;
691 sk_sp<SkShader> shader =
692 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500693 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800694 paint.setShader(shader);
695 clearRegion.setRects(skRects, numRects);
696 canvas->drawRegion(clearRegion, paint);
697 }
698
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500699 // setup color filter if necessary
700 sk_sp<SkColorFilter> displayColorTransform;
701 if (display.colorTransform != mat4()) {
702 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
703 }
704
John Reck67b1e2b2020-08-26 13:17:24 -0700705 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500706 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100707
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500708 sk_sp<SkImage> blurInput;
709 if (blurCompositionLayer == layer) {
710 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
711 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
712
713 // save a snapshot of the activeSurface to use as input to the blur shaders
714 blurInput = activeSurface->makeImageSnapshot();
715
716 // TODO we could skip this step if we know the blur will cover the entire image
717 // blit the offscreen framebuffer into the destination AHB
718 SkPaint paint;
719 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500720 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
721 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
722 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
723 String8::format("SurfaceID|%" PRId64, id).c_str(),
724 nullptr);
725 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
726 } else {
727 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
728 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500729
730 // assign dstCanvas to canvas and ensure that the canvas state is up to date
731 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500732 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500733 initCanvas(canvas, display);
734
735 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
736 dstSurface->getCanvas()->getSaveCount());
737 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
738 dstSurface->getCanvas()->getTotalMatrix());
739
740 // assign dstSurface to activeSurface
741 activeSurface = dstSurface;
742 }
743
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500744 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500745 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800746 // Record the name of the layer if the capture is running.
747 std::stringstream layerSettings;
748 PrintTo(*layer, &layerSettings);
749 // Store the LayerSettings in additional information.
750 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
751 SkData::MakeWithCString(layerSettings.str().c_str()));
752 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100753 // Layers have a local transform that should be applied to them
754 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100755
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500756 const auto bounds = getSkRect(layer->geometry.boundaries);
757 if (mBlurFilter && layerHasBlur(layer)) {
758 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
759
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500760 // if multiple layers have blur, then we need to take a snapshot now because
761 // only the lowest layer will have blurImage populated earlier
762 if (!blurInput) {
763 blurInput = activeSurface->makeImageSnapshot();
764 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500765 // rect to be blurred in the coordinate space of blurInput
766 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
767
Lucas Dupinc3800b82020-10-02 16:24:48 -0700768 if (layer->backgroundBlurRadius > 0) {
769 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500770 auto blurredImage =
771 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
772 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100773
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500774 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
775
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500776 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
777 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700778 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500779 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100780 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700781 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500782 cachedBlurs[region.blurRadius] =
783 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
784 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700785 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500786
787 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
788 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700789 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700790 }
791
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500792 // Shadows are assumed to live only on their own layer - it's not valid
793 // to draw the boundary rectangles when there is already a caster shadow
794 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
795 // composition - using a well-defined invalid color is long-term less error-prone.
796 if (layer->shadow.length > 0) {
797 const auto rect = layer->geometry.roundedCornersRadius > 0
798 ? getSkRect(layer->geometry.roundedCornersCrop)
799 : bounds;
800 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
801 continue;
802 }
803
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500804 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
805 (mUseColorManagement &&
806 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
807
808 // quick abort from drawing the remaining portion of the layer
809 if (layer->alpha == 0 && !requiresLinearEffect &&
810 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
811 continue;
812 }
813
814 // If we need to map to linear space or color management is disabled, then mark the source
815 // image with the same colorspace as the destination surface so that Skia's color
816 // management is a no-op.
817 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
818 ? dstDataspace
819 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800820
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500821 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700822 if (layer->source.buffer.buffer) {
823 ATRACE_NAME("DrawImage");
Ady Abraham193426d2021-02-18 14:01:53 -0800824 validateInputBufferUsage(layer->source.buffer.buffer);
John Reck67b1e2b2020-08-26 13:17:24 -0700825 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800826 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
827 auto iter = mTextureCache.find(item.buffer->getId());
828 if (iter != mTextureCache.end()) {
829 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700830 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800831 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800832 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800833 item.buffer->toAHardwareBuffer(),
834 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800835 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700836 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800837
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800838 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500839 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800840 item.usePremultipliedAlpha
841 ? kPremul_SkAlphaType
842 : kUnpremul_SkAlphaType,
843 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700844
845 auto texMatrix = getSkM44(item.textureTransform).asM33();
846 // textureTansform was intended to be passed directly into a shader, so when
847 // building the total matrix with the textureTransform we need to first
848 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500849 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800850 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700851
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800852 SkMatrix matrix;
853 if (!texMatrix.invert(&matrix)) {
854 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700855 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800856 // The shader does not respect the translation, so we add it to the texture
857 // transform for the SkImage. This will make sure that the correct layer contents
858 // are drawn in the correct part of the screen.
859 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700860
Ana Krulecb7b28b22020-11-23 14:48:58 -0800861 sk_sp<SkShader> shader;
862
863 if (layer->source.buffer.useTextureFiltering) {
864 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
865 SkSamplingOptions(
866 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
867 &matrix);
868 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500869 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800870 }
Alec Mouri029d1952020-10-12 10:37:08 -0700871
Alec Mouric0aae732021-01-12 13:32:18 -0800872 // Handle opaque images - it's a little nonstandard how we do this.
873 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
874 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
875 // The important language is that when isOpaque is set, opacity is not sampled from the
876 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
877 // here's the conundrum:
878 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
879 // as an internal hint - composition is undefined when there are alpha bits present.
880 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
881 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
882 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
883 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
884 // of a hack anyways.
885 // 3. We can't change the blendmode to src, because while this satisfies the requirement
886 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
887 // because src always clobbers the destination content.
888 //
889 // So, what we do here instead is an additive blend mode where we compose the input
890 // image with a solid black. This might need to be reassess if this does not support
891 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
892 if (item.isOpaque) {
893 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
894 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500895 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800896 }
897
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500898 paint.setShader(createRuntimeEffectShader(shader, layer, display,
899 !item.isOpaque && item.usePremultipliedAlpha,
900 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800901 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700902 } else {
903 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700904 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800905 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
906 .fG = color.g,
907 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800908 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500909 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800910 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500911 /* undoPremultipliedAlpha */ false,
912 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700913 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700914
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500915 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700916
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500917 if (layer->geometry.roundedCornersRadius > 0) {
918 paint.setAntiAlias(true);
919 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800920 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500921 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700922 }
John Reck67b1e2b2020-08-26 13:17:24 -0700923 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500924 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800925 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700926 {
927 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500928 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
929 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700930 }
931
932 if (drawFence != nullptr) {
933 *drawFence = flush();
934 }
935
936 // If flush failed or we don't support native fences, we need to force the
937 // gl command stream to be executed.
938 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
939 if (requireSync) {
940 ATRACE_BEGIN("Submit(sync=true)");
941 } else {
942 ATRACE_BEGIN("Submit(sync=false)");
943 }
Lucas Dupind508e472020-11-04 04:32:06 +0000944 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700945 ATRACE_END();
946 if (!success) {
947 ALOGE("Failed to flush RenderEngine commands");
948 // Chances are, something illegal happened (either the caller passed
949 // us bad parameters, or we messed up our shader generation).
950 return INVALID_OPERATION;
951 }
952
953 // checkErrors();
954 return NO_ERROR;
955}
956
Lucas Dupin3f11e922020-09-22 17:31:04 -0700957inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
958 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
959}
960
961inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
962 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
963}
964
Lucas Dupin21f348e2020-09-16 17:31:26 -0700965inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800966 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700967 const auto cornerRadius = layer->geometry.roundedCornersRadius;
968 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
969}
970
Galia Peycheva80116e52020-11-06 11:57:25 +0100971inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
972 const auto rect = getSkRect(layer->geometry.boundaries);
973 const auto cornersRadius = layer->geometry.roundedCornersRadius;
974 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
975 .cornerRadiusTL = cornersRadius,
976 .cornerRadiusTR = cornersRadius,
977 .cornerRadiusBL = cornersRadius,
978 .cornerRadiusBR = cornersRadius,
979 .alpha = 1,
980 .left = static_cast<int>(rect.fLeft),
981 .top = static_cast<int>(rect.fTop),
982 .right = static_cast<int>(rect.fRight),
983 .bottom = static_cast<int>(rect.fBottom)};
984}
985
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500986inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
987 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
988}
989
Lucas Dupin3f11e922020-09-22 17:31:04 -0700990inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
991 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
992}
993
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700994inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
995 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
996 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
997 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
998 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
999}
1000
Lucas Dupin3f11e922020-09-22 17:31:04 -07001001inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1002 return SkPoint3::Make(vector.x, vector.y, vector.z);
1003}
1004
John Reck67b1e2b2020-08-26 13:17:24 -07001005size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1006 return mGrContext->maxTextureSize();
1007}
1008
1009size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1010 return mGrContext->maxRenderTargetSize();
1011}
1012
Lucas Dupin3f11e922020-09-22 17:31:04 -07001013void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1014 const ShadowSettings& settings) {
1015 ATRACE_CALL();
1016 const float casterZ = settings.length / 2.0f;
1017 const auto shadowShape = cornerRadius > 0
1018 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1019 : SkPath::Rect(casterRect);
1020 const auto flags =
1021 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1022
1023 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1024 getSkPoint3(settings.lightPos), settings.lightRadius,
1025 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1026 flags);
1027}
1028
John Reck67b1e2b2020-08-26 13:17:24 -07001029EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001030 EGLContext shareContext,
1031 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001032 Protection protection) {
1033 EGLint renderableType = 0;
1034 if (config == EGL_NO_CONFIG_KHR) {
1035 renderableType = EGL_OPENGL_ES3_BIT;
1036 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1037 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1038 }
1039 EGLint contextClientVersion = 0;
1040 if (renderableType & EGL_OPENGL_ES3_BIT) {
1041 contextClientVersion = 3;
1042 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1043 contextClientVersion = 2;
1044 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1045 contextClientVersion = 1;
1046 } else {
1047 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1048 }
1049
1050 std::vector<EGLint> contextAttributes;
1051 contextAttributes.reserve(7);
1052 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1053 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001054 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001055 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001056 switch (*contextPriority) {
1057 case ContextPriority::REALTIME:
1058 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1059 break;
1060 case ContextPriority::MEDIUM:
1061 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1062 break;
1063 case ContextPriority::LOW:
1064 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1065 break;
1066 case ContextPriority::HIGH:
1067 default:
1068 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1069 break;
1070 }
John Reck67b1e2b2020-08-26 13:17:24 -07001071 }
1072 if (protection == Protection::PROTECTED) {
1073 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1074 contextAttributes.push_back(EGL_TRUE);
1075 }
1076 contextAttributes.push_back(EGL_NONE);
1077
1078 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1079
1080 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1081 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1082 // EGL_NO_CONTEXT so that we can abort.
1083 if (config != EGL_NO_CONFIG_KHR) {
1084 return context;
1085 }
1086 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1087 // should try to fall back to GLES 2.
1088 contextAttributes[1] = 2;
1089 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1090 }
1091
1092 return context;
1093}
1094
Alec Mourid6f09462020-12-07 11:18:17 -08001095std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1096 const RenderEngineCreationArgs& args) {
1097 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1098 return std::nullopt;
1099 }
1100
1101 switch (args.contextPriority) {
1102 case RenderEngine::ContextPriority::REALTIME:
1103 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1104 return RenderEngine::ContextPriority::REALTIME;
1105 } else {
1106 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1107 return RenderEngine::ContextPriority::HIGH;
1108 }
1109 case RenderEngine::ContextPriority::HIGH:
1110 case RenderEngine::ContextPriority::MEDIUM:
1111 case RenderEngine::ContextPriority::LOW:
1112 return args.contextPriority;
1113 default:
1114 return std::nullopt;
1115 }
1116}
1117
John Reck67b1e2b2020-08-26 13:17:24 -07001118EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1119 EGLConfig config, int hwcFormat,
1120 Protection protection) {
1121 EGLConfig placeholderConfig = config;
1122 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1123 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1124 }
1125 std::vector<EGLint> attributes;
1126 attributes.reserve(7);
1127 attributes.push_back(EGL_WIDTH);
1128 attributes.push_back(1);
1129 attributes.push_back(EGL_HEIGHT);
1130 attributes.push_back(1);
1131 if (protection == Protection::PROTECTED) {
1132 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1133 attributes.push_back(EGL_TRUE);
1134 }
1135 attributes.push_back(EGL_NONE);
1136
1137 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1138}
1139
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001140void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -07001141
Alec Mourid6f09462020-12-07 11:18:17 -08001142int SkiaGLRenderEngine::getContextPriority() {
1143 int value;
1144 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1145 return value;
1146}
1147
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001148void SkiaGLRenderEngine::dump(std::string& result) {
1149 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1150
1151 StringAppendF(&result, "\n ------------RE-----------------\n");
1152 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1153 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1154 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1155 extensions.getVersion());
1156 StringAppendF(&result, "%s\n", extensions.getExtensions());
1157 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1158 supportsProtectedContent());
1159 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1160
1161 {
1162 std::lock_guard<std::mutex> lock(mRenderingMutex);
1163 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1164 StringAppendF(&result, "Dumping buffer ids...\n");
1165 // TODO(178539829): It would be nice to know which layer these are coming from and what
1166 // the texture sizes are.
1167 for (const auto& [id, unused] : mTextureCache) {
1168 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1169 }
1170 StringAppendF(&result, "\n");
1171 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1172 mProtectedTextureCache.size());
1173 StringAppendF(&result, "Dumping buffer ids...\n");
1174 for (const auto& [id, unused] : mProtectedTextureCache) {
1175 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1176 }
1177 StringAppendF(&result, "\n");
1178 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1179 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1180 StringAppendF(&result, "- inputDataspace: %s\n",
1181 dataspaceDetails(
1182 static_cast<android_dataspace>(linearEffect.inputDataspace))
1183 .c_str());
1184 StringAppendF(&result, "- outputDataspace: %s\n",
1185 dataspaceDetails(
1186 static_cast<android_dataspace>(linearEffect.outputDataspace))
1187 .c_str());
1188 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1189 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1190 }
1191 }
1192 StringAppendF(&result, "\n");
1193}
1194
John Reck67b1e2b2020-08-26 13:17:24 -07001195} // namespace skia
1196} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001197} // namespace android