blob: 1719cd88460d3670e28f757a05d62e7c8f36d38a [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
Alec Mouri678245d2020-09-30 16:58:23 -070018#include <cstdint>
John Reck67b1e2b2020-08-26 13:17:24 -070019#undef LOG_TAG
20#define LOG_TAG "RenderEngine"
21#define ATRACE_TAG ATRACE_TAG_GRAPHICS
22
Alec Mourib5777452020-09-28 11:32:42 -070023#include "SkiaGLRenderEngine.h"
John Reck67b1e2b2020-08-26 13:17:24 -070024
25#include <EGL/egl.h>
26#include <EGL/eglext.h>
27#include <GLES2/gl2.h>
John Reck67b1e2b2020-08-26 13:17:24 -070028#include <GrContextOptions.h>
John Reck67b1e2b2020-08-26 13:17:24 -070029#include <SkCanvas.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>
Lucas Dupin3f11e922020-09-22 17:31:04 -070033#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070034#include <SkSurface.h>
Alec Mourib5777452020-09-28 11:32:42 -070035#include <gl/GrGLInterface.h>
36#include <sync/sync.h>
37#include <ui/GraphicBuffer.h>
38#include <utils/Trace.h>
39
40#include <cmath>
41
42#include "../gl/GLExtensions.h"
43#include "filters/BlurFilter.h"
John Reck67b1e2b2020-08-26 13:17:24 -070044
45extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
46
47bool checkGlError(const char* op, int lineNumber);
48
49namespace android {
50namespace renderengine {
51namespace skia {
52
53static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
54 EGLint wanted, EGLConfig* outConfig) {
55 EGLint numConfigs = -1, n = 0;
56 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
57 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
58 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
59 configs.resize(n);
60
61 if (!configs.empty()) {
62 if (attribute != EGL_NONE) {
63 for (EGLConfig config : configs) {
64 EGLint value = 0;
65 eglGetConfigAttrib(dpy, config, attribute, &value);
66 if (wanted == value) {
67 *outConfig = config;
68 return NO_ERROR;
69 }
70 }
71 } else {
72 // just pick the first one
73 *outConfig = configs[0];
74 return NO_ERROR;
75 }
76 }
77
78 return NAME_NOT_FOUND;
79}
80
81static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
82 EGLConfig* config) {
83 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
84 // it is to be used with WIFI displays
85 status_t err;
86 EGLint wantedAttribute;
87 EGLint wantedAttributeValue;
88
89 std::vector<EGLint> attribs;
90 if (renderableType) {
91 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
92 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
93
94 // Default to 8 bits per channel.
95 const EGLint tmpAttribs[] = {
96 EGL_RENDERABLE_TYPE,
97 renderableType,
98 EGL_RECORDABLE_ANDROID,
99 EGL_TRUE,
100 EGL_SURFACE_TYPE,
101 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
102 EGL_FRAMEBUFFER_TARGET_ANDROID,
103 EGL_TRUE,
104 EGL_RED_SIZE,
105 is1010102 ? 10 : 8,
106 EGL_GREEN_SIZE,
107 is1010102 ? 10 : 8,
108 EGL_BLUE_SIZE,
109 is1010102 ? 10 : 8,
110 EGL_ALPHA_SIZE,
111 is1010102 ? 2 : 8,
112 EGL_NONE,
113 };
114 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
115 std::back_inserter(attribs));
116 wantedAttribute = EGL_NONE;
117 wantedAttributeValue = EGL_NONE;
118 } else {
119 // if no renderable type specified, fallback to a simplified query
120 wantedAttribute = EGL_NATIVE_VISUAL_ID;
121 wantedAttributeValue = format;
122 }
123
124 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
125 config);
126 if (err == NO_ERROR) {
127 EGLint caveat;
128 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
129 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
130 }
131
132 return err;
133}
134
Alec Mourib5777452020-09-28 11:32:42 -0700135// Converts an android dataspace to a supported SkColorSpace
136// Supported dataspaces are
137// 1. sRGB
138// 2. Display P3
139// 3. BT2020 PQ
140// 4. BT2020 HLG
141// Unknown primaries are mapped to BT709, and unknown transfer functions
142// are mapped to sRGB.
143static sk_sp<SkColorSpace> toColorSpace(ui::Dataspace dataspace) {
144 skcms_Matrix3x3 gamut;
145 switch (dataspace & HAL_DATASPACE_STANDARD_MASK) {
146 case HAL_DATASPACE_STANDARD_BT709:
147 gamut = SkNamedGamut::kSRGB;
148 break;
149 case HAL_DATASPACE_STANDARD_BT2020:
150 gamut = SkNamedGamut::kRec2020;
151 break;
152 case HAL_DATASPACE_STANDARD_DCI_P3:
153 gamut = SkNamedGamut::kDisplayP3;
154 break;
155 default:
156 ALOGV("Unsupported Gamut: %d, defaulting to sRGB", dataspace);
157 gamut = SkNamedGamut::kSRGB;
158 break;
159 }
160
161 switch (dataspace & HAL_DATASPACE_TRANSFER_MASK) {
162 case HAL_DATASPACE_TRANSFER_LINEAR:
163 return SkColorSpace::MakeRGB(SkNamedTransferFn::kLinear, gamut);
164 case HAL_DATASPACE_TRANSFER_SRGB:
165 return SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, gamut);
166 case HAL_DATASPACE_TRANSFER_ST2084:
167 return SkColorSpace::MakeRGB(SkNamedTransferFn::kPQ, gamut);
168 case HAL_DATASPACE_TRANSFER_HLG:
169 return SkColorSpace::MakeRGB(SkNamedTransferFn::kHLG, gamut);
170 default:
171 ALOGV("Unsupported Gamma: %d, defaulting to sRGB transfer", dataspace);
172 return SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, gamut);
173 }
174}
175
John Reck67b1e2b2020-08-26 13:17:24 -0700176std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
177 const RenderEngineCreationArgs& args) {
178 // initialize EGL for the default display
179 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
180 if (!eglInitialize(display, nullptr, nullptr)) {
181 LOG_ALWAYS_FATAL("failed to initialize EGL");
182 }
183
184 const auto eglVersion = eglQueryStringImplementationANDROID(display, EGL_VERSION);
185 if (!eglVersion) {
186 checkGlError(__FUNCTION__, __LINE__);
187 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_VERSION) failed");
188 }
189
190 const auto eglExtensions = eglQueryStringImplementationANDROID(display, EGL_EXTENSIONS);
191 if (!eglExtensions) {
192 checkGlError(__FUNCTION__, __LINE__);
193 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_EXTENSIONS) failed");
194 }
195
196 auto& extensions = gl::GLExtensions::getInstance();
197 extensions.initWithEGLStrings(eglVersion, eglExtensions);
198
199 // The code assumes that ES2 or later is available if this extension is
200 // supported.
201 EGLConfig config = EGL_NO_CONFIG_KHR;
202 if (!extensions.hasNoConfigContext()) {
203 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
204 }
205
206 bool useContextPriority =
207 extensions.hasContextPriority() && args.contextPriority == ContextPriority::HIGH;
208 EGLContext protectedContext = EGL_NO_CONTEXT;
209 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
210 protectedContext = createEglContext(display, config, nullptr, useContextPriority,
211 Protection::PROTECTED);
212 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
213 }
214
215 EGLContext ctxt = createEglContext(display, config, protectedContext, useContextPriority,
216 Protection::UNPROTECTED);
217
218 // if can't create a GL context, we can only abort.
219 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
220
221 EGLSurface placeholder = EGL_NO_SURFACE;
222 if (!extensions.hasSurfacelessContext()) {
223 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
224 Protection::UNPROTECTED);
225 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
226 }
227 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
228 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
229 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
230 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
231
232 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
233 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
234 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
235 Protection::PROTECTED);
236 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
237 "can't create protected placeholder pbuffer");
238 }
239
240 // initialize the renderer while GL is current
241 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700242 std::make_unique<SkiaGLRenderEngine>(args, display, config, ctxt, placeholder,
John Reck67b1e2b2020-08-26 13:17:24 -0700243 protectedContext, protectedPlaceholder);
244
245 ALOGI("OpenGL ES informations:");
246 ALOGI("vendor : %s", extensions.getVendor());
247 ALOGI("renderer : %s", extensions.getRenderer());
248 ALOGI("version : %s", extensions.getVersion());
249 ALOGI("extensions: %s", extensions.getExtensions());
250 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
251 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
252
253 return engine;
254}
255
256EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
257 status_t err;
258 EGLConfig config;
259
260 // First try to get an ES3 config
261 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
262 if (err != NO_ERROR) {
263 // If ES3 fails, try to get an ES2 config
264 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
265 if (err != NO_ERROR) {
266 // If ES2 still doesn't work, probably because we're on the emulator.
267 // try a simplified query
268 ALOGW("no suitable EGLConfig found, trying a simpler query");
269 err = selectEGLConfig(display, format, 0, &config);
270 if (err != NO_ERROR) {
271 // this EGL is too lame for android
272 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
273 }
274 }
275 }
276
277 if (logConfig) {
278 // print some debugging info
279 EGLint r, g, b, a;
280 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
281 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
282 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
283 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
284 ALOGI("EGL information:");
285 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
286 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
287 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
288 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
289 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
290 }
291
292 return config;
293}
294
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700295SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
296 EGLConfig config, EGLContext ctxt, EGLSurface placeholder,
297 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri081be4c2020-09-16 10:24:47 -0700298 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700299 mEGLConfig(config),
300 mEGLContext(ctxt),
301 mPlaceholderSurface(placeholder),
302 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700303 mProtectedPlaceholderSurface(protectedPlaceholder),
304 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700305 // Suppress unused field warnings for things we definitely will need/use
306 // These EGL fields will all be needed for toggling between protected & unprotected contexts
307 // Or we need different RE instances for that
308 (void)mEGLDisplay;
309 (void)mEGLConfig;
310 (void)mEGLContext;
311 (void)mPlaceholderSurface;
312 (void)mProtectedEGLContext;
313 (void)mProtectedPlaceholderSurface;
314
315 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
316 LOG_ALWAYS_FATAL_IF(!glInterface.get());
317
318 GrContextOptions options;
319 options.fPreferExternalImagesOverES3 = true;
320 options.fDisableDistanceFieldPaths = true;
321 mGrContext = GrDirectContext::MakeGL(std::move(glInterface), options);
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700322
323 if (args.supportsBackgroundBlur) {
324 mBlurFilter = new BlurFilter();
325 }
John Reck67b1e2b2020-08-26 13:17:24 -0700326}
327
328base::unique_fd SkiaGLRenderEngine::flush() {
329 ATRACE_CALL();
330 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
331 return base::unique_fd();
332 }
333
334 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
335 if (sync == EGL_NO_SYNC_KHR) {
336 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
337 return base::unique_fd();
338 }
339
340 // native fence fd will not be populated until flush() is done.
341 glFlush();
342
343 // get the fence fd
344 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
345 eglDestroySyncKHR(mEGLDisplay, sync);
346 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
347 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
348 }
349
350 return fenceFd;
351}
352
353bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
354 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
355 !gl::GLExtensions::getInstance().hasWaitSync()) {
356 return false;
357 }
358
359 // release the fd and transfer the ownership to EGLSync
360 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
361 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
362 if (sync == EGL_NO_SYNC_KHR) {
363 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
364 return false;
365 }
366
367 // XXX: The spec draft is inconsistent as to whether this should return an
368 // EGLint or void. Ignore the return value for now, as it's not strictly
369 // needed.
370 eglWaitSyncKHR(mEGLDisplay, sync, 0);
371 EGLint error = eglGetError();
372 eglDestroySyncKHR(mEGLDisplay, sync);
373 if (error != EGL_SUCCESS) {
374 ALOGE("failed to wait for EGL native fence sync: %#x", error);
375 return false;
376 }
377
378 return true;
379}
380
381static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
382 return !!(desc.usage & usage);
383}
384
Alec Mouri678245d2020-09-30 16:58:23 -0700385static float toDegrees(uint32_t transform) {
386 switch (transform) {
387 case ui::Transform::ROT_90:
388 return 90.0;
389 case ui::Transform::ROT_180:
390 return 180.0;
391 case ui::Transform::ROT_270:
392 return 270.0;
393 default:
394 return 0.0;
395 }
396}
397
John Reck67b1e2b2020-08-26 13:17:24 -0700398void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
399 std::lock_guard<std::mutex> lock(mRenderingMutex);
400 mImageCache.erase(bufferId);
401}
402
403status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
404 const std::vector<const LayerSettings*>& layers,
405 const sp<GraphicBuffer>& buffer,
406 const bool useFramebufferCache,
407 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
408 ATRACE_NAME("SkiaGL::drawLayers");
409 std::lock_guard<std::mutex> lock(mRenderingMutex);
410 if (layers.empty()) {
411 ALOGV("Drawing empty layer stack");
412 return NO_ERROR;
413 }
414
415 if (bufferFence.get() >= 0) {
416 // Duplicate the fence for passing to waitFence.
417 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
418 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
419 ATRACE_NAME("Waiting before draw");
420 sync_wait(bufferFence.get(), -1);
421 }
422 }
423 if (buffer == nullptr) {
424 ALOGE("No output buffer provided. Aborting GPU composition.");
425 return BAD_VALUE;
426 }
427
428 AHardwareBuffer_Desc bufferDesc;
429 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
430
431 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
432 "missing usage");
433
434 sk_sp<SkSurface> surface;
435 if (useFramebufferCache) {
436 auto iter = mSurfaceCache.find(buffer->getId());
437 if (iter != mSurfaceCache.end()) {
438 ALOGV("Cache hit!");
439 surface = iter->second;
440 }
441 }
442 if (!surface) {
443 surface = SkSurface::MakeFromAHardwareBuffer(mGrContext.get(), buffer->toAHardwareBuffer(),
444 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
Alec Mourib5777452020-09-28 11:32:42 -0700445 mUseColorManagement
446 ? toColorSpace(display.outputDataspace)
447 : SkColorSpace::MakeSRGB(),
448 nullptr);
John Reck67b1e2b2020-08-26 13:17:24 -0700449 if (useFramebufferCache && surface) {
450 ALOGD("Adding to cache");
451 mSurfaceCache.insert({buffer->getId(), surface});
452 }
453 }
454 if (!surface) {
455 ALOGE("Failed to make surface");
456 return BAD_VALUE;
457 }
Alec Mouri678245d2020-09-30 16:58:23 -0700458
John Reck67b1e2b2020-08-26 13:17:24 -0700459 auto canvas = surface->getCanvas();
Alec Mouri678245d2020-09-30 16:58:23 -0700460 // Clear the entire canvas with a transparent black to prevent ghost images.
461 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700462 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700463
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700464 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
465 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
466 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700467
468 canvas->clipRect(getSkRect(display.physicalDisplay));
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700469 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700470
471 const auto clipWidth = display.clip.width();
472 const auto clipHeight = display.clip.height();
473 auto rotatedClipWidth = clipWidth;
474 auto rotatedClipHeight = clipHeight;
475 // Scale is contingent on the rotation result.
476 if (display.orientation & ui::Transform::ROT_90) {
477 std::swap(rotatedClipWidth, rotatedClipHeight);
478 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700479 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700480 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700481 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700482 static_cast<SkScalar>(rotatedClipHeight);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700483 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700484
485 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
486 // back so that the top left corner of the clip is at (0, 0).
487 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
488 canvas->rotate(toDegrees(display.orientation));
489 canvas->translate(-clipWidth / 2, -clipHeight / 2);
490 canvas->translate(-display.clip.left, -display.clip.top);
John Reck67b1e2b2020-08-26 13:17:24 -0700491 for (const auto& layer : layers) {
Lucas Dupin21f348e2020-09-16 17:31:26 -0700492 SkPaint paint;
493 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700494 const auto dest = getSkRect(bounds);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700495
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700496 if (layer->backgroundBlurRadius > 0) {
497 ATRACE_NAME("BackgroundBlur");
498 mBlurFilter->draw(canvas, surface, layer->backgroundBlurRadius);
499 }
500
John Reck67b1e2b2020-08-26 13:17:24 -0700501 if (layer->source.buffer.buffer) {
502 ATRACE_NAME("DrawImage");
503 const auto& item = layer->source.buffer;
Alec Mouri678245d2020-09-30 16:58:23 -0700504 const auto bufferWidth = item.buffer->getBounds().width();
505 const auto bufferHeight = item.buffer->getBounds().height();
John Reck67b1e2b2020-08-26 13:17:24 -0700506 sk_sp<SkImage> image;
507 auto iter = mImageCache.find(item.buffer->getId());
508 if (iter != mImageCache.end()) {
509 image = iter->second;
510 } else {
511 image = SkImage::MakeFromAHardwareBuffer(item.buffer->toAHardwareBuffer(),
512 item.usePremultipliedAlpha
513 ? kPremul_SkAlphaType
Alec Mourib5777452020-09-28 11:32:42 -0700514 : kUnpremul_SkAlphaType,
515 mUseColorManagement
516 ? toColorSpace(
517 layer->sourceDataspace)
518 : SkColorSpace::MakeSRGB());
John Reck67b1e2b2020-08-26 13:17:24 -0700519 mImageCache.insert({item.buffer->getId(), image});
520 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700521
522 SkMatrix matrix;
523 if (layer->geometry.roundedCornersRadius > 0) {
524 const auto roundedRect = getRoundedRect(layer);
525 matrix.setTranslate(roundedRect.getBounds().left() - dest.left(),
526 roundedRect.getBounds().top() - dest.top());
527 } else {
528 matrix.setIdentity();
529 }
Alec Mouri678245d2020-09-30 16:58:23 -0700530
531 auto texMatrix = getSkM44(item.textureTransform).asM33();
532 // textureTansform was intended to be passed directly into a shader, so when
533 // building the total matrix with the textureTransform we need to first
534 // normalize it, then apply the textureTransform, then scale back up.
535 matrix.postScale(1.0f / bufferWidth, 1.0f / bufferHeight);
536
537 auto rotatedBufferWidth = bufferWidth;
538 auto rotatedBufferHeight = bufferHeight;
539
540 // Swap the buffer width and height if we're rotating, so that we
541 // scale back up by the correct factors post-rotation.
542 if (texMatrix.getSkewX() <= -0.5f || texMatrix.getSkewX() >= 0.5f) {
543 std::swap(rotatedBufferWidth, rotatedBufferHeight);
544 // TODO: clean this up.
545 // GLESRenderEngine specifies its texture coordinates in
546 // CW orientation under OpenGL conventions, when they probably should have
547 // been CCW instead. The net result is that orientation
548 // transforms are applied in the reverse
549 // direction to render the correct result, because SurfaceFlinger uses the inverse
550 // of the display transform to correct for that. But this means that
551 // the tex transform passed by SkiaGLRenderEngine will rotate
552 // individual layers in the reverse orientation. Hack around it
553 // by injected a 180 degree rotation, but ultimately this is
554 // a bug in how SurfaceFlinger invokes the RenderEngine
555 // interface, so the proper fix should live there, and GLESRenderEngine
556 // should be fixed accordingly.
557 matrix.postRotate(180, 0.5, 0.5);
558 }
559
560 matrix.postConcat(texMatrix);
561 matrix.postScale(rotatedBufferWidth, rotatedBufferHeight);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700562 paint.setShader(image->makeShader(matrix));
John Reck67b1e2b2020-08-26 13:17:24 -0700563 } else {
564 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700565 const auto color = layer->source.solidColor;
566 paint.setColor(SkColor4f{.fR = color.r, .fG = color.g, .fB = color.b, layer->alpha});
567 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700568
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700569 // Layers have a local transform matrix that should be applied to them.
570 canvas->save();
571 canvas->concat(getSkM44(layer->geometry.positionTransform));
572
Lucas Dupin3f11e922020-09-22 17:31:04 -0700573 if (layer->shadow.length > 0) {
574 const auto rect = layer->geometry.roundedCornersRadius > 0
575 ? getSkRect(layer->geometry.roundedCornersCrop)
576 : dest;
577 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
578 }
579
Lucas Dupin21f348e2020-09-16 17:31:26 -0700580 if (layer->geometry.roundedCornersRadius > 0) {
581 canvas->drawRRect(getRoundedRect(layer), paint);
582 } else {
583 canvas->drawRect(dest, paint);
584 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700585 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700586 }
587 {
588 ATRACE_NAME("flush surface");
589 surface->flush();
590 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700591 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700592
593 if (drawFence != nullptr) {
594 *drawFence = flush();
595 }
596
597 // If flush failed or we don't support native fences, we need to force the
598 // gl command stream to be executed.
599 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
600 if (requireSync) {
601 ATRACE_BEGIN("Submit(sync=true)");
602 } else {
603 ATRACE_BEGIN("Submit(sync=false)");
604 }
605 bool success = mGrContext->submit(requireSync);
606 ATRACE_END();
607 if (!success) {
608 ALOGE("Failed to flush RenderEngine commands");
609 // Chances are, something illegal happened (either the caller passed
610 // us bad parameters, or we messed up our shader generation).
611 return INVALID_OPERATION;
612 }
613
614 // checkErrors();
615 return NO_ERROR;
616}
617
Lucas Dupin3f11e922020-09-22 17:31:04 -0700618inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
619 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
620}
621
622inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
623 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
624}
625
Lucas Dupin21f348e2020-09-16 17:31:26 -0700626inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Lucas Dupin3f11e922020-09-22 17:31:04 -0700627 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700628 const auto cornerRadius = layer->geometry.roundedCornersRadius;
629 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
630}
631
Lucas Dupin3f11e922020-09-22 17:31:04 -0700632inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
633 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
634}
635
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700636inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
637 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
638 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
639 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
640 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
641}
642
Lucas Dupin3f11e922020-09-22 17:31:04 -0700643inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
644 return SkPoint3::Make(vector.x, vector.y, vector.z);
645}
646
John Reck67b1e2b2020-08-26 13:17:24 -0700647size_t SkiaGLRenderEngine::getMaxTextureSize() const {
648 return mGrContext->maxTextureSize();
649}
650
651size_t SkiaGLRenderEngine::getMaxViewportDims() const {
652 return mGrContext->maxRenderTargetSize();
653}
654
Lucas Dupin3f11e922020-09-22 17:31:04 -0700655void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
656 const ShadowSettings& settings) {
657 ATRACE_CALL();
658 const float casterZ = settings.length / 2.0f;
659 const auto shadowShape = cornerRadius > 0
660 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
661 : SkPath::Rect(casterRect);
662 const auto flags =
663 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
664
665 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
666 getSkPoint3(settings.lightPos), settings.lightRadius,
667 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
668 flags);
669}
670
John Reck67b1e2b2020-08-26 13:17:24 -0700671EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
672 EGLContext shareContext, bool useContextPriority,
673 Protection protection) {
674 EGLint renderableType = 0;
675 if (config == EGL_NO_CONFIG_KHR) {
676 renderableType = EGL_OPENGL_ES3_BIT;
677 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
678 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
679 }
680 EGLint contextClientVersion = 0;
681 if (renderableType & EGL_OPENGL_ES3_BIT) {
682 contextClientVersion = 3;
683 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
684 contextClientVersion = 2;
685 } else if (renderableType & EGL_OPENGL_ES_BIT) {
686 contextClientVersion = 1;
687 } else {
688 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
689 }
690
691 std::vector<EGLint> contextAttributes;
692 contextAttributes.reserve(7);
693 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
694 contextAttributes.push_back(contextClientVersion);
695 if (useContextPriority) {
696 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
697 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
698 }
699 if (protection == Protection::PROTECTED) {
700 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
701 contextAttributes.push_back(EGL_TRUE);
702 }
703 contextAttributes.push_back(EGL_NONE);
704
705 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
706
707 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
708 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
709 // EGL_NO_CONTEXT so that we can abort.
710 if (config != EGL_NO_CONFIG_KHR) {
711 return context;
712 }
713 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
714 // should try to fall back to GLES 2.
715 contextAttributes[1] = 2;
716 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
717 }
718
719 return context;
720}
721
722EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
723 EGLConfig config, int hwcFormat,
724 Protection protection) {
725 EGLConfig placeholderConfig = config;
726 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
727 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
728 }
729 std::vector<EGLint> attributes;
730 attributes.reserve(7);
731 attributes.push_back(EGL_WIDTH);
732 attributes.push_back(1);
733 attributes.push_back(EGL_HEIGHT);
734 attributes.push_back(1);
735 if (protection == Protection::PROTECTED) {
736 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
737 attributes.push_back(EGL_TRUE);
738 }
739 attributes.push_back(EGL_NONE);
740
741 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
742}
743
744void SkiaGLRenderEngine::cleanFramebufferCache() {
745 mSurfaceCache.clear();
746}
747
748} // namespace skia
749} // namespace renderengine
750} // namespace android