blob: 7cfe207c1e9ae545319c28423bd8d7a633574955 [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
18#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include <cmath>
23
24#include <EGL/egl.h>
25#include <EGL/eglext.h>
26#include <GLES2/gl2.h>
27#include <sync/sync.h>
28#include <ui/GraphicBuffer.h>
29#include <utils/Trace.h>
30#include "../gl/GLExtensions.h"
31#include "SkiaGLRenderEngine.h"
32
33#include <GrContextOptions.h>
34#include <gl/GrGLInterface.h>
35
36#include <SkCanvas.h>
37#include <SkImage.h>
38#include <SkSurface.h>
39
40extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
41
42bool checkGlError(const char* op, int lineNumber);
43
44namespace android {
45namespace renderengine {
46namespace skia {
47
48static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
49 EGLint wanted, EGLConfig* outConfig) {
50 EGLint numConfigs = -1, n = 0;
51 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
52 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
53 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
54 configs.resize(n);
55
56 if (!configs.empty()) {
57 if (attribute != EGL_NONE) {
58 for (EGLConfig config : configs) {
59 EGLint value = 0;
60 eglGetConfigAttrib(dpy, config, attribute, &value);
61 if (wanted == value) {
62 *outConfig = config;
63 return NO_ERROR;
64 }
65 }
66 } else {
67 // just pick the first one
68 *outConfig = configs[0];
69 return NO_ERROR;
70 }
71 }
72
73 return NAME_NOT_FOUND;
74}
75
76static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
77 EGLConfig* config) {
78 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
79 // it is to be used with WIFI displays
80 status_t err;
81 EGLint wantedAttribute;
82 EGLint wantedAttributeValue;
83
84 std::vector<EGLint> attribs;
85 if (renderableType) {
86 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
87 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
88
89 // Default to 8 bits per channel.
90 const EGLint tmpAttribs[] = {
91 EGL_RENDERABLE_TYPE,
92 renderableType,
93 EGL_RECORDABLE_ANDROID,
94 EGL_TRUE,
95 EGL_SURFACE_TYPE,
96 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
97 EGL_FRAMEBUFFER_TARGET_ANDROID,
98 EGL_TRUE,
99 EGL_RED_SIZE,
100 is1010102 ? 10 : 8,
101 EGL_GREEN_SIZE,
102 is1010102 ? 10 : 8,
103 EGL_BLUE_SIZE,
104 is1010102 ? 10 : 8,
105 EGL_ALPHA_SIZE,
106 is1010102 ? 2 : 8,
107 EGL_NONE,
108 };
109 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
110 std::back_inserter(attribs));
111 wantedAttribute = EGL_NONE;
112 wantedAttributeValue = EGL_NONE;
113 } else {
114 // if no renderable type specified, fallback to a simplified query
115 wantedAttribute = EGL_NATIVE_VISUAL_ID;
116 wantedAttributeValue = format;
117 }
118
119 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
120 config);
121 if (err == NO_ERROR) {
122 EGLint caveat;
123 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
124 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
125 }
126
127 return err;
128}
129
130std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
131 const RenderEngineCreationArgs& args) {
132 // initialize EGL for the default display
133 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
134 if (!eglInitialize(display, nullptr, nullptr)) {
135 LOG_ALWAYS_FATAL("failed to initialize EGL");
136 }
137
138 const auto eglVersion = eglQueryStringImplementationANDROID(display, EGL_VERSION);
139 if (!eglVersion) {
140 checkGlError(__FUNCTION__, __LINE__);
141 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_VERSION) failed");
142 }
143
144 const auto eglExtensions = eglQueryStringImplementationANDROID(display, EGL_EXTENSIONS);
145 if (!eglExtensions) {
146 checkGlError(__FUNCTION__, __LINE__);
147 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_EXTENSIONS) failed");
148 }
149
150 auto& extensions = gl::GLExtensions::getInstance();
151 extensions.initWithEGLStrings(eglVersion, eglExtensions);
152
153 // The code assumes that ES2 or later is available if this extension is
154 // supported.
155 EGLConfig config = EGL_NO_CONFIG_KHR;
156 if (!extensions.hasNoConfigContext()) {
157 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
158 }
159
160 bool useContextPriority =
161 extensions.hasContextPriority() && args.contextPriority == ContextPriority::HIGH;
162 EGLContext protectedContext = EGL_NO_CONTEXT;
163 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
164 protectedContext = createEglContext(display, config, nullptr, useContextPriority,
165 Protection::PROTECTED);
166 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
167 }
168
169 EGLContext ctxt = createEglContext(display, config, protectedContext, useContextPriority,
170 Protection::UNPROTECTED);
171
172 // if can't create a GL context, we can only abort.
173 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
174
175 EGLSurface placeholder = EGL_NO_SURFACE;
176 if (!extensions.hasSurfacelessContext()) {
177 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
178 Protection::UNPROTECTED);
179 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
180 }
181 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
182 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
183 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
184 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
185
186 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
187 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
188 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
189 Protection::PROTECTED);
190 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
191 "can't create protected placeholder pbuffer");
192 }
193
194 // initialize the renderer while GL is current
195 std::unique_ptr<SkiaGLRenderEngine> engine =
Alec Mouri081be4c2020-09-16 10:24:47 -0700196 std::make_unique<SkiaGLRenderEngine>(display, config, ctxt, placeholder,
John Reck67b1e2b2020-08-26 13:17:24 -0700197 protectedContext, protectedPlaceholder);
198
199 ALOGI("OpenGL ES informations:");
200 ALOGI("vendor : %s", extensions.getVendor());
201 ALOGI("renderer : %s", extensions.getRenderer());
202 ALOGI("version : %s", extensions.getVersion());
203 ALOGI("extensions: %s", extensions.getExtensions());
204 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
205 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
206
207 return engine;
208}
209
210EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
211 status_t err;
212 EGLConfig config;
213
214 // First try to get an ES3 config
215 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
216 if (err != NO_ERROR) {
217 // If ES3 fails, try to get an ES2 config
218 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
219 if (err != NO_ERROR) {
220 // If ES2 still doesn't work, probably because we're on the emulator.
221 // try a simplified query
222 ALOGW("no suitable EGLConfig found, trying a simpler query");
223 err = selectEGLConfig(display, format, 0, &config);
224 if (err != NO_ERROR) {
225 // this EGL is too lame for android
226 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
227 }
228 }
229 }
230
231 if (logConfig) {
232 // print some debugging info
233 EGLint r, g, b, a;
234 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
235 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
236 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
237 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
238 ALOGI("EGL information:");
239 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
240 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
241 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
242 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
243 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
244 }
245
246 return config;
247}
248
Alec Mouri081be4c2020-09-16 10:24:47 -0700249SkiaGLRenderEngine::SkiaGLRenderEngine(EGLDisplay display, EGLConfig config, EGLContext ctxt,
250 EGLSurface placeholder, EGLContext protectedContext,
251 EGLSurface protectedPlaceholder)
252 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700253 mEGLConfig(config),
254 mEGLContext(ctxt),
255 mPlaceholderSurface(placeholder),
256 mProtectedEGLContext(protectedContext),
257 mProtectedPlaceholderSurface(protectedPlaceholder) {
258 // Suppress unused field warnings for things we definitely will need/use
259 // These EGL fields will all be needed for toggling between protected & unprotected contexts
260 // Or we need different RE instances for that
261 (void)mEGLDisplay;
262 (void)mEGLConfig;
263 (void)mEGLContext;
264 (void)mPlaceholderSurface;
265 (void)mProtectedEGLContext;
266 (void)mProtectedPlaceholderSurface;
267
268 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
269 LOG_ALWAYS_FATAL_IF(!glInterface.get());
270
271 GrContextOptions options;
272 options.fPreferExternalImagesOverES3 = true;
273 options.fDisableDistanceFieldPaths = true;
274 mGrContext = GrDirectContext::MakeGL(std::move(glInterface), options);
275}
276
277base::unique_fd SkiaGLRenderEngine::flush() {
278 ATRACE_CALL();
279 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
280 return base::unique_fd();
281 }
282
283 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
284 if (sync == EGL_NO_SYNC_KHR) {
285 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
286 return base::unique_fd();
287 }
288
289 // native fence fd will not be populated until flush() is done.
290 glFlush();
291
292 // get the fence fd
293 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
294 eglDestroySyncKHR(mEGLDisplay, sync);
295 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
296 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
297 }
298
299 return fenceFd;
300}
301
302bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
303 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
304 !gl::GLExtensions::getInstance().hasWaitSync()) {
305 return false;
306 }
307
308 // release the fd and transfer the ownership to EGLSync
309 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
310 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
311 if (sync == EGL_NO_SYNC_KHR) {
312 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
313 return false;
314 }
315
316 // XXX: The spec draft is inconsistent as to whether this should return an
317 // EGLint or void. Ignore the return value for now, as it's not strictly
318 // needed.
319 eglWaitSyncKHR(mEGLDisplay, sync, 0);
320 EGLint error = eglGetError();
321 eglDestroySyncKHR(mEGLDisplay, sync);
322 if (error != EGL_SUCCESS) {
323 ALOGE("failed to wait for EGL native fence sync: %#x", error);
324 return false;
325 }
326
327 return true;
328}
329
330static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
331 return !!(desc.usage & usage);
332}
333
334void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
335 std::lock_guard<std::mutex> lock(mRenderingMutex);
336 mImageCache.erase(bufferId);
337}
338
339status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
340 const std::vector<const LayerSettings*>& layers,
341 const sp<GraphicBuffer>& buffer,
342 const bool useFramebufferCache,
343 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
344 ATRACE_NAME("SkiaGL::drawLayers");
345 std::lock_guard<std::mutex> lock(mRenderingMutex);
346 if (layers.empty()) {
347 ALOGV("Drawing empty layer stack");
348 return NO_ERROR;
349 }
350
351 if (bufferFence.get() >= 0) {
352 // Duplicate the fence for passing to waitFence.
353 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
354 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
355 ATRACE_NAME("Waiting before draw");
356 sync_wait(bufferFence.get(), -1);
357 }
358 }
359 if (buffer == nullptr) {
360 ALOGE("No output buffer provided. Aborting GPU composition.");
361 return BAD_VALUE;
362 }
363
364 AHardwareBuffer_Desc bufferDesc;
365 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
366
367 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
368 "missing usage");
369
370 sk_sp<SkSurface> surface;
371 if (useFramebufferCache) {
372 auto iter = mSurfaceCache.find(buffer->getId());
373 if (iter != mSurfaceCache.end()) {
374 ALOGV("Cache hit!");
375 surface = iter->second;
376 }
377 }
378 if (!surface) {
379 surface = SkSurface::MakeFromAHardwareBuffer(mGrContext.get(), buffer->toAHardwareBuffer(),
380 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
381 SkColorSpace::MakeSRGB(), nullptr);
382 if (useFramebufferCache && surface) {
383 ALOGD("Adding to cache");
384 mSurfaceCache.insert({buffer->getId(), surface});
385 }
386 }
387 if (!surface) {
388 ALOGE("Failed to make surface");
389 return BAD_VALUE;
390 }
391 auto canvas = surface->getCanvas();
392
393 canvas->clipRect(SkRect::MakeLTRB(display.clip.left, display.clip.top, display.clip.right,
394 display.clip.bottom));
395 canvas->drawColor(0, SkBlendMode::kSrc);
396 for (const auto& layer : layers) {
397 if (layer->source.buffer.buffer) {
398 ATRACE_NAME("DrawImage");
399 const auto& item = layer->source.buffer;
400 sk_sp<SkImage> image;
401 auto iter = mImageCache.find(item.buffer->getId());
402 if (iter != mImageCache.end()) {
403 image = iter->second;
404 } else {
405 image = SkImage::MakeFromAHardwareBuffer(item.buffer->toAHardwareBuffer(),
406 item.usePremultipliedAlpha
407 ? kPremul_SkAlphaType
408 : kUnpremul_SkAlphaType);
409 mImageCache.insert({item.buffer->getId(), image});
410 }
411 const auto& bounds = layer->geometry.boundaries;
412 SkRect dest = SkRect::MakeLTRB(bounds.left, bounds.top, bounds.right, bounds.bottom);
413 canvas->drawImageRect(image, dest, nullptr);
414 } else {
415 ATRACE_NAME("DrawColor");
416 SkPaint paint;
417 const auto color = layer->source.solidColor;
418 paint.setColor(SkColor4f{.fR = color.r, .fG = color.g, .fB = color.b, layer->alpha});
419 }
420 }
421 {
422 ATRACE_NAME("flush surface");
423 surface->flush();
424 }
425
426 if (drawFence != nullptr) {
427 *drawFence = flush();
428 }
429
430 // If flush failed or we don't support native fences, we need to force the
431 // gl command stream to be executed.
432 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
433 if (requireSync) {
434 ATRACE_BEGIN("Submit(sync=true)");
435 } else {
436 ATRACE_BEGIN("Submit(sync=false)");
437 }
438 bool success = mGrContext->submit(requireSync);
439 ATRACE_END();
440 if (!success) {
441 ALOGE("Failed to flush RenderEngine commands");
442 // Chances are, something illegal happened (either the caller passed
443 // us bad parameters, or we messed up our shader generation).
444 return INVALID_OPERATION;
445 }
446
447 // checkErrors();
448 return NO_ERROR;
449}
450
451size_t SkiaGLRenderEngine::getMaxTextureSize() const {
452 return mGrContext->maxTextureSize();
453}
454
455size_t SkiaGLRenderEngine::getMaxViewportDims() const {
456 return mGrContext->maxRenderTargetSize();
457}
458
459EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
460 EGLContext shareContext, bool useContextPriority,
461 Protection protection) {
462 EGLint renderableType = 0;
463 if (config == EGL_NO_CONFIG_KHR) {
464 renderableType = EGL_OPENGL_ES3_BIT;
465 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
466 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
467 }
468 EGLint contextClientVersion = 0;
469 if (renderableType & EGL_OPENGL_ES3_BIT) {
470 contextClientVersion = 3;
471 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
472 contextClientVersion = 2;
473 } else if (renderableType & EGL_OPENGL_ES_BIT) {
474 contextClientVersion = 1;
475 } else {
476 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
477 }
478
479 std::vector<EGLint> contextAttributes;
480 contextAttributes.reserve(7);
481 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
482 contextAttributes.push_back(contextClientVersion);
483 if (useContextPriority) {
484 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
485 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
486 }
487 if (protection == Protection::PROTECTED) {
488 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
489 contextAttributes.push_back(EGL_TRUE);
490 }
491 contextAttributes.push_back(EGL_NONE);
492
493 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
494
495 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
496 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
497 // EGL_NO_CONTEXT so that we can abort.
498 if (config != EGL_NO_CONFIG_KHR) {
499 return context;
500 }
501 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
502 // should try to fall back to GLES 2.
503 contextAttributes[1] = 2;
504 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
505 }
506
507 return context;
508}
509
510EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
511 EGLConfig config, int hwcFormat,
512 Protection protection) {
513 EGLConfig placeholderConfig = config;
514 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
515 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
516 }
517 std::vector<EGLint> attributes;
518 attributes.reserve(7);
519 attributes.push_back(EGL_WIDTH);
520 attributes.push_back(1);
521 attributes.push_back(EGL_HEIGHT);
522 attributes.push_back(1);
523 if (protection == Protection::PROTECTED) {
524 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
525 attributes.push_back(EGL_TRUE);
526 }
527 attributes.push_back(EGL_NONE);
528
529 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
530}
531
532void SkiaGLRenderEngine::cleanFramebufferCache() {
533 mSurfaceCache.clear();
534}
535
536} // namespace skia
537} // namespace renderengine
538} // namespace android