blob: afdcd765529f199ceac499f0df0c032b5aca88f1 [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() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100301 cleanFramebufferCache();
Alec Mouric0aae732021-01-12 13:32:18 -0800302
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100303 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800304 if (mBlurFilter) {
305 delete mBlurFilter;
306 }
307
308 mCapture = nullptr;
309
310 mGrContext->flushAndSubmit(true);
311 mGrContext->abandonContext();
312
313 if (mProtectedGrContext) {
314 mProtectedGrContext->flushAndSubmit(true);
315 mProtectedGrContext->abandonContext();
316 }
317
318 if (mPlaceholderSurface != EGL_NO_SURFACE) {
319 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
320 }
321 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
322 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
323 }
324 if (mEGLContext != EGL_NO_CONTEXT) {
325 eglDestroyContext(mEGLDisplay, mEGLContext);
326 }
327 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
328 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
329 }
330 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
331 eglTerminate(mEGLDisplay);
332 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700333}
334
Lucas Dupind508e472020-11-04 04:32:06 +0000335bool SkiaGLRenderEngine::supportsProtectedContent() const {
336 return mProtectedEGLContext != EGL_NO_CONTEXT;
337}
338
339bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
340 if (useProtectedContext == mInProtectedContext) {
341 return true;
342 }
Alec Mourif6a07812021-02-11 21:07:55 -0800343 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000344 return false;
345 }
346 const EGLSurface surface =
347 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
348 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
349 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800350
Lucas Dupind508e472020-11-04 04:32:06 +0000351 if (success) {
352 mInProtectedContext = useProtectedContext;
353 }
354 return success;
355}
356
John Reck67b1e2b2020-08-26 13:17:24 -0700357base::unique_fd SkiaGLRenderEngine::flush() {
358 ATRACE_CALL();
359 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
360 return base::unique_fd();
361 }
362
363 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
364 if (sync == EGL_NO_SYNC_KHR) {
365 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
366 return base::unique_fd();
367 }
368
369 // native fence fd will not be populated until flush() is done.
370 glFlush();
371
372 // get the fence fd
373 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
374 eglDestroySyncKHR(mEGLDisplay, sync);
375 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
376 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
377 }
378
379 return fenceFd;
380}
381
382bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
383 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
384 !gl::GLExtensions::getInstance().hasWaitSync()) {
385 return false;
386 }
387
388 // release the fd and transfer the ownership to EGLSync
389 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
390 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
391 if (sync == EGL_NO_SYNC_KHR) {
392 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
393 return false;
394 }
395
396 // XXX: The spec draft is inconsistent as to whether this should return an
397 // EGLint or void. Ignore the return value for now, as it's not strictly
398 // needed.
399 eglWaitSyncKHR(mEGLDisplay, sync, 0);
400 EGLint error = eglGetError();
401 eglDestroySyncKHR(mEGLDisplay, sync);
402 if (error != EGL_SUCCESS) {
403 ALOGE("failed to wait for EGL native fence sync: %#x", error);
404 return false;
405 }
406
407 return true;
408}
409
Alec Mouri678245d2020-09-30 16:58:23 -0700410static float toDegrees(uint32_t transform) {
411 switch (transform) {
412 case ui::Transform::ROT_90:
413 return 90.0;
414 case ui::Transform::ROT_180:
415 return 180.0;
416 case ui::Transform::ROT_270:
417 return 270.0;
418 default:
419 return 0.0;
420 }
421}
422
Alec Mourib34f0b72020-10-02 13:18:34 -0700423static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
424 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
425 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
426 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
427 matrix[3][3], 0);
428}
429
Alec Mouri029d1952020-10-12 10:37:08 -0700430static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
431 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
432 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
433
434 // Treat unsupported dataspaces as srgb
435 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
436 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
437 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
438 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
439 }
440
441 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
442 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
443 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
444 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
445 }
446
447 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
448 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
449 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
450 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
451
452 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
453 sourceTransfer != destTransfer;
454}
455
Ana Krulecdfec8f52021-01-13 12:51:47 -0800456void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
457 // Only run this if RE is running on its own thread. This way the access to GL
458 // operations is guaranteed to be happening on the same thread.
459 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
460 return;
461 }
462 ATRACE_CALL();
463
464 std::lock_guard<std::mutex> lock(mRenderingMutex);
465 auto iter = mTextureCache.find(buffer->getId());
466 if (iter != mTextureCache.end()) {
467 ALOGV("Texture already exists in cache.");
468 return;
469 } else {
470 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
471 std::make_shared<AutoBackendTexture::LocalRef>();
472 imageTextureRef->setTexture(
473 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), false));
474 mTextureCache.insert({buffer->getId(), imageTextureRef});
475 }
476}
477
John Reck67b1e2b2020-08-26 13:17:24 -0700478void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800479 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700480 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800481 mTextureCache.erase(bufferId);
482 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700483}
484
Ana Krulec47814212021-01-06 19:00:10 -0800485sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
486 const LayerSettings* layer,
487 const DisplaySettings& display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500488 bool undoPremultipliedAlpha,
489 bool requiresLinearEffect) {
John Reckcdb4ed72021-02-04 13:39:33 -0500490 if (layer->stretchEffect.hasEffect()) {
491 // TODO: Implement
492 }
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500493 if (requiresLinearEffect) {
494 const ui::Dataspace inputDataspace =
495 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
496 const ui::Dataspace outputDataspace =
497 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
498
499 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
500 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800501 .undoPremultipliedAlpha = undoPremultipliedAlpha};
502
503 auto effectIter = mRuntimeEffects.find(effect);
504 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
505 if (effectIter == mRuntimeEffects.end()) {
506 runtimeEffect = buildRuntimeEffect(effect);
507 mRuntimeEffects.insert({effect, runtimeEffect});
508 } else {
509 runtimeEffect = effectIter->second;
510 }
511 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
512 display.maxLuminance,
513 layer->source.buffer.maxMasteringLuminance,
514 layer->source.buffer.maxContentLuminance);
515 }
516 return shader;
517}
518
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500519void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500520 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500521 // Record display settings when capture is running.
522 std::stringstream displaySettings;
523 PrintTo(display, &displaySettings);
524 // Store the DisplaySettings in additional information.
525 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
526 SkData::MakeWithCString(displaySettings.str().c_str()));
527 }
528
529 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
530 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
531 // displays might have different scaling when compared to the physical screen.
532
533 canvas->clipRect(getSkRect(display.physicalDisplay));
534 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
535
536 const auto clipWidth = display.clip.width();
537 const auto clipHeight = display.clip.height();
538 auto rotatedClipWidth = clipWidth;
539 auto rotatedClipHeight = clipHeight;
540 // Scale is contingent on the rotation result.
541 if (display.orientation & ui::Transform::ROT_90) {
542 std::swap(rotatedClipWidth, rotatedClipHeight);
543 }
544 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
545 static_cast<SkScalar>(rotatedClipWidth);
546 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
547 static_cast<SkScalar>(rotatedClipHeight);
548 canvas->scale(scaleX, scaleY);
549
550 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
551 // back so that the top left corner of the clip is at (0, 0).
552 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
553 canvas->rotate(toDegrees(display.orientation));
554 canvas->translate(-clipWidth / 2, -clipHeight / 2);
555 canvas->translate(-display.clip.left, -display.clip.top);
556}
557
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500558class AutoSaveRestore {
559public:
560 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
561 ~AutoSaveRestore() { restore(); }
562 void replace(SkCanvas* canvas) {
563 mCanvas = canvas;
564 mSaveCount = canvas->save();
565 }
566 void restore() {
567 if (mCanvas) {
568 mCanvas->restoreToCount(mSaveCount);
569 mCanvas = nullptr;
570 }
571 }
572
573private:
574 SkCanvas* mCanvas;
575 int mSaveCount;
576};
577
John Reck67b1e2b2020-08-26 13:17:24 -0700578status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
579 const std::vector<const LayerSettings*>& layers,
580 const sp<GraphicBuffer>& buffer,
581 const bool useFramebufferCache,
582 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
583 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800584
John Reck67b1e2b2020-08-26 13:17:24 -0700585 std::lock_guard<std::mutex> lock(mRenderingMutex);
586 if (layers.empty()) {
587 ALOGV("Drawing empty layer stack");
588 return NO_ERROR;
589 }
590
591 if (bufferFence.get() >= 0) {
592 // Duplicate the fence for passing to waitFence.
593 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
594 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
595 ATRACE_NAME("Waiting before draw");
596 sync_wait(bufferFence.get(), -1);
597 }
598 }
599 if (buffer == nullptr) {
600 ALOGE("No output buffer provided. Aborting GPU composition.");
601 return BAD_VALUE;
602 }
603
Ady Abraham193426d2021-02-18 14:01:53 -0800604 validateOutputBufferUsage(buffer);
605
Lucas Dupind508e472020-11-04 04:32:06 +0000606 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800607 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700608 AHardwareBuffer_Desc bufferDesc;
609 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700610
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800611 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700612 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000613 auto iter = cache.find(buffer->getId());
614 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700615 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800616 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800617 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700618 }
619 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800620
621 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800622 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800623 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
624 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800625 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800626 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700627 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800628 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700629 }
630 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800631
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500632 const ui::Dataspace dstDataspace =
633 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500634 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500635 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700636
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500637 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
638 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800639 ALOGE("Cannot acquire canvas from Skia.");
640 return BAD_VALUE;
641 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500642
643 // Find if any layers have requested blur, we'll use that info to decide when to render to an
644 // offscreen buffer and when to render to the native buffer.
645 sk_sp<SkSurface> activeSurface(dstSurface);
646 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500647 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500648 const LayerSettings* blurCompositionLayer = nullptr;
649 if (mBlurFilter) {
650 bool requiresCompositionLayer = false;
651 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500652 if (layer->backgroundBlurRadius > 0 &&
653 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500654 requiresCompositionLayer = true;
655 }
656 for (auto region : layer->blurRegions) {
657 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
658 requiresCompositionLayer = true;
659 }
660 }
661 if (requiresCompositionLayer) {
662 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500663 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500664 blurCompositionLayer = layer;
665 break;
666 }
667 }
668 }
669
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500670 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700671 // Clear the entire canvas with a transparent black to prevent ghost images.
672 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500673 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800674
675 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
676 // view is still on-screen. The clear region could be re-specified as a black color layer,
677 // however.
678 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500679 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800680 size_t numRects = 0;
681 Rect const* rects = display.clearRegion.getArray(&numRects);
682 SkIRect skRects[numRects];
683 for (int i = 0; i < numRects; ++i) {
684 skRects[i] =
685 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
686 }
687 SkRegion clearRegion;
688 SkPaint paint;
689 sk_sp<SkShader> shader =
690 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500691 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800692 paint.setShader(shader);
693 clearRegion.setRects(skRects, numRects);
694 canvas->drawRegion(clearRegion, paint);
695 }
696
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500697 // setup color filter if necessary
698 sk_sp<SkColorFilter> displayColorTransform;
699 if (display.colorTransform != mat4()) {
700 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
701 }
702
John Reck67b1e2b2020-08-26 13:17:24 -0700703 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500704 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100705
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500706 sk_sp<SkImage> blurInput;
707 if (blurCompositionLayer == layer) {
708 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
709 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
710
711 // save a snapshot of the activeSurface to use as input to the blur shaders
712 blurInput = activeSurface->makeImageSnapshot();
713
714 // TODO we could skip this step if we know the blur will cover the entire image
715 // blit the offscreen framebuffer into the destination AHB
716 SkPaint paint;
717 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500718 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
719 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
720 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
721 String8::format("SurfaceID|%" PRId64, id).c_str(),
722 nullptr);
723 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
724 } else {
725 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
726 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500727
728 // assign dstCanvas to canvas and ensure that the canvas state is up to date
729 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500730 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500731 initCanvas(canvas, display);
732
733 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
734 dstSurface->getCanvas()->getSaveCount());
735 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
736 dstSurface->getCanvas()->getTotalMatrix());
737
738 // assign dstSurface to activeSurface
739 activeSurface = dstSurface;
740 }
741
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500742 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500743 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800744 // Record the name of the layer if the capture is running.
745 std::stringstream layerSettings;
746 PrintTo(*layer, &layerSettings);
747 // Store the LayerSettings in additional information.
748 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
749 SkData::MakeWithCString(layerSettings.str().c_str()));
750 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100751 // Layers have a local transform that should be applied to them
752 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100753
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500754 const auto bounds = getSkRect(layer->geometry.boundaries);
755 if (mBlurFilter && layerHasBlur(layer)) {
756 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
757
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500758 // if multiple layers have blur, then we need to take a snapshot now because
759 // only the lowest layer will have blurImage populated earlier
760 if (!blurInput) {
761 blurInput = activeSurface->makeImageSnapshot();
762 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500763 // rect to be blurred in the coordinate space of blurInput
764 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
765
Lucas Dupinc3800b82020-10-02 16:24:48 -0700766 if (layer->backgroundBlurRadius > 0) {
767 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500768 auto blurredImage =
769 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
770 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100771
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500772 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
773
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500774 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
775 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700776 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500777 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100778 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700779 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500780 cachedBlurs[region.blurRadius] =
781 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
782 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700783 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500784
785 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
786 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700787 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700788 }
789
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500790 // Shadows are assumed to live only on their own layer - it's not valid
791 // to draw the boundary rectangles when there is already a caster shadow
792 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
793 // composition - using a well-defined invalid color is long-term less error-prone.
794 if (layer->shadow.length > 0) {
795 const auto rect = layer->geometry.roundedCornersRadius > 0
796 ? getSkRect(layer->geometry.roundedCornersCrop)
797 : bounds;
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400798 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
799 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500800 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
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400809 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500810 (!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
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400915 if (layer->disableBlending) {
916 paint.setBlendMode(SkBlendMode::kSrc);
917 }
918
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
Marin Shalamanovcea12ef2021-03-15 17:00:51 +01001144void SkiaGLRenderEngine::cleanFramebufferCache() {
1145 // TODO(b/180767535) Remove this method and use b/180767535 instead, which would allow
1146 // SF to control texture lifecycle more tightly rather than through custom hooks into RE.
1147 std::lock_guard<std::mutex> lock(mRenderingMutex);
1148 mRuntimeEffects.clear();
1149 mProtectedTextureCache.clear();
1150 mTextureCache.clear();
1151}
John Reck67b1e2b2020-08-26 13:17:24 -07001152
Alec Mourid6f09462020-12-07 11:18:17 -08001153int SkiaGLRenderEngine::getContextPriority() {
1154 int value;
1155 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1156 return value;
1157}
1158
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001159void SkiaGLRenderEngine::dump(std::string& result) {
1160 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1161
1162 StringAppendF(&result, "\n ------------RE-----------------\n");
1163 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1164 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1165 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1166 extensions.getVersion());
1167 StringAppendF(&result, "%s\n", extensions.getExtensions());
1168 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1169 supportsProtectedContent());
1170 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1171
1172 {
1173 std::lock_guard<std::mutex> lock(mRenderingMutex);
1174 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1175 StringAppendF(&result, "Dumping buffer ids...\n");
1176 // TODO(178539829): It would be nice to know which layer these are coming from and what
1177 // the texture sizes are.
1178 for (const auto& [id, unused] : mTextureCache) {
1179 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1180 }
1181 StringAppendF(&result, "\n");
1182 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1183 mProtectedTextureCache.size());
1184 StringAppendF(&result, "Dumping buffer ids...\n");
1185 for (const auto& [id, unused] : mProtectedTextureCache) {
1186 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1187 }
1188 StringAppendF(&result, "\n");
1189 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1190 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1191 StringAppendF(&result, "- inputDataspace: %s\n",
1192 dataspaceDetails(
1193 static_cast<android_dataspace>(linearEffect.inputDataspace))
1194 .c_str());
1195 StringAppendF(&result, "- outputDataspace: %s\n",
1196 dataspaceDetails(
1197 static_cast<android_dataspace>(linearEffect.outputDataspace))
1198 .c_str());
1199 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1200 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1201 }
1202 }
1203 StringAppendF(&result, "\n");
1204}
1205
John Reck67b1e2b2020-08-26 13:17:24 -07001206} // namespace skia
1207} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001208} // namespace android