blob: e523836c59df8bcd9f6344b5ba3aedce7fa39bfc [file] [log] [blame]
Mathias Agopian3f844832013-08-07 21:24:32 -07001/*
2 * Copyright 2013 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
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
Mathias Agopian3f844832013-08-07 21:24:32 -070020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Alec Mouri16a99402019-07-29 16:37:30 -070022#include <sched.h>
23#include <cmath>
Peiyong Lin833074a2018-08-28 11:53:54 -070024#include <fstream>
25#include <sstream>
Alec Mouri0d5e1eb2018-11-10 20:40:12 -080026#include <unordered_set>
Peiyong Lincbc184f2018-08-22 13:24:10 -070027
Mathias Agopian3f844832013-08-07 21:24:32 -070028#include <GLES2/gl2.h>
Mathias Agopian458197d2013-08-15 14:56:51 -070029#include <GLES2/gl2ext.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080030#include <android-base/stringprintf.h>
Peiyong Lin833074a2018-08-28 11:53:54 -070031#include <cutils/compiler.h>
Alec Mouri554d06e2018-12-20 00:15:33 -080032#include <cutils/properties.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070033#include <gui/DebugEGLImageTracker.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070034#include <renderengine/Mesh.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070035#include <renderengine/Texture.h>
Peiyong Lin833074a2018-08-28 11:53:54 -070036#include <renderengine/private/Description.h>
Alec Mouri0d5e1eb2018-11-10 20:40:12 -080037#include <sync/sync.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060038#include <ui/ColorSpace.h>
39#include <ui/DebugUtils.h>
Alec Mourida4cf3b2019-02-12 15:33:01 -080040#include <ui/GraphicBuffer.h>
Dan Stozac1879002014-05-22 15:59:05 -070041#include <ui/Rect.h>
Peiyong Lin60bedb52018-09-05 10:47:31 -070042#include <ui/Region.h>
Chia-I Wu56d7b0a2018-10-01 15:13:11 -070043#include <utils/KeyedVector.h>
Mathias Agopian3f844832013-08-07 21:24:32 -070044#include <utils/Trace.h>
Alec Mouri16a99402019-07-29 16:37:30 -070045#include "GLESRenderEngine.h"
Peiyong Linf1bada92018-08-29 09:39:31 -070046#include "GLExtensions.h"
Peiyong Line5a9a7f2018-08-30 15:32:13 -070047#include "GLFramebuffer.h"
Peiyong Linf1bada92018-08-29 09:39:31 -070048#include "GLImage.h"
Vishnu Nair16efdbf2019-12-10 11:55:42 -080049#include "GLShadowVertexGenerator.h"
Peiyong Lin833074a2018-08-28 11:53:54 -070050#include "Program.h"
51#include "ProgramCache.h"
Lucas Dupin19c8f0e2019-11-25 17:55:44 -080052#include "filters/BlurFilter.h"
53#include "filters/GaussianBlurFilter.h"
Lucas Dupin453932d2020-02-03 20:42:25 -080054#include "filters/KawaseBlurFilter.h"
Mathias Agopian3f844832013-08-07 21:24:32 -070055
Peiyong Linf11f39b2018-09-05 14:37:41 -070056extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
57
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060058bool checkGlError(const char* op, int lineNumber) {
59 bool errorFound = false;
60 GLint error = glGetError();
61 while (error != GL_NO_ERROR) {
62 errorFound = true;
63 error = glGetError();
64 ALOGV("after %s() (line # %d) glError (0x%x)\n", op, lineNumber, error);
65 }
66 return errorFound;
67}
68
Courtney Goeltzenleuchter4f20f9c2017-04-06 08:18:34 -060069static constexpr bool outputDebugPPMs = false;
70
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060071void writePPM(const char* basename, GLuint width, GLuint height) {
72 ALOGV("writePPM #%s: %d x %d", basename, width, height);
73
74 std::vector<GLubyte> pixels(width * height * 4);
75 std::vector<GLubyte> outBuffer(width * height * 3);
76
77 // TODO(courtneygo): We can now have float formats, need
78 // to remove this code or update to support.
79 // Make returned pixels fit in uint32_t, one byte per component
80 glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
81 if (checkGlError(__FUNCTION__, __LINE__)) {
82 return;
83 }
84
85 std::string filename(basename);
86 filename.append(".ppm");
87 std::ofstream file(filename.c_str(), std::ios::binary);
88 if (!file.is_open()) {
89 ALOGE("Unable to open file: %s", filename.c_str());
90 ALOGE("You may need to do: \"adb shell setenforce 0\" to enable "
91 "surfaceflinger to write debug images");
92 return;
93 }
94
95 file << "P6\n";
96 file << width << "\n";
97 file << height << "\n";
98 file << 255 << "\n";
99
100 auto ptr = reinterpret_cast<char*>(pixels.data());
101 auto outPtr = reinterpret_cast<char*>(outBuffer.data());
102 for (int y = height - 1; y >= 0; y--) {
103 char* data = ptr + y * width * sizeof(uint32_t);
104
105 for (GLuint x = 0; x < width; x++) {
106 // Only copy R, G and B components
107 outPtr[0] = data[0];
108 outPtr[1] = data[1];
109 outPtr[2] = data[2];
110 data += sizeof(uint32_t);
111 outPtr += 3;
112 }
113 }
114 file.write(reinterpret_cast<char*>(outBuffer.data()), outBuffer.size());
115}
116
Mathias Agopian3f844832013-08-07 21:24:32 -0700117namespace android {
Peiyong Lin833074a2018-08-28 11:53:54 -0700118namespace renderengine {
119namespace gl {
Mathias Agopian3f844832013-08-07 21:24:32 -0700120
Yiwei Zhang5434a782018-12-05 18:06:32 -0800121using base::StringAppendF;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700122using ui::Dataspace;
123
Peiyong Linf11f39b2018-09-05 14:37:41 -0700124static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
125 EGLint wanted, EGLConfig* outConfig) {
126 EGLint numConfigs = -1, n = 0;
127 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
Chia-I Wud3b13cb2018-09-13 13:31:26 -0700128 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
129 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
130 configs.resize(n);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700131
Chia-I Wud3b13cb2018-09-13 13:31:26 -0700132 if (!configs.empty()) {
Peiyong Linf11f39b2018-09-05 14:37:41 -0700133 if (attribute != EGL_NONE) {
Chia-I Wud3b13cb2018-09-13 13:31:26 -0700134 for (EGLConfig config : configs) {
Peiyong Linf11f39b2018-09-05 14:37:41 -0700135 EGLint value = 0;
Chia-I Wud3b13cb2018-09-13 13:31:26 -0700136 eglGetConfigAttrib(dpy, config, attribute, &value);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700137 if (wanted == value) {
Chia-I Wud3b13cb2018-09-13 13:31:26 -0700138 *outConfig = config;
Peiyong Linf11f39b2018-09-05 14:37:41 -0700139 return NO_ERROR;
140 }
141 }
142 } else {
143 // just pick the first one
144 *outConfig = configs[0];
Peiyong Linf11f39b2018-09-05 14:37:41 -0700145 return NO_ERROR;
146 }
147 }
Chia-I Wud3b13cb2018-09-13 13:31:26 -0700148
Peiyong Linf11f39b2018-09-05 14:37:41 -0700149 return NAME_NOT_FOUND;
150}
151
152class EGLAttributeVector {
153 struct Attribute;
154 class Adder;
155 friend class Adder;
156 KeyedVector<Attribute, EGLint> mList;
157 struct Attribute {
158 Attribute() : v(0){};
159 explicit Attribute(EGLint v) : v(v) {}
160 EGLint v;
161 bool operator<(const Attribute& other) const {
162 // this places EGL_NONE at the end
163 EGLint lhs(v);
164 EGLint rhs(other.v);
165 if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
166 if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
167 return lhs < rhs;
168 }
169 };
170 class Adder {
171 friend class EGLAttributeVector;
172 EGLAttributeVector& v;
173 EGLint attribute;
174 Adder(EGLAttributeVector& v, EGLint attribute) : v(v), attribute(attribute) {}
175
176 public:
177 void operator=(EGLint value) {
178 if (attribute != EGL_NONE) {
179 v.mList.add(Attribute(attribute), value);
180 }
181 }
182 operator EGLint() const { return v.mList[attribute]; }
183 };
184
185public:
186 EGLAttributeVector() { mList.add(Attribute(EGL_NONE), EGL_NONE); }
187 void remove(EGLint attribute) {
188 if (attribute != EGL_NONE) {
189 mList.removeItem(Attribute(attribute));
190 }
191 }
192 Adder operator[](EGLint attribute) { return Adder(*this, attribute); }
193 EGLint operator[](EGLint attribute) const { return mList[attribute]; }
194 // cast-operator to (EGLint const*)
195 operator EGLint const*() const { return &mList.keyAt(0).v; }
196};
197
198static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
199 EGLConfig* config) {
200 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
201 // it is to be used with WIFI displays
202 status_t err;
203 EGLint wantedAttribute;
204 EGLint wantedAttributeValue;
205
206 EGLAttributeVector attribs;
207 if (renderableType) {
208 attribs[EGL_RENDERABLE_TYPE] = renderableType;
209 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE;
210 attribs[EGL_SURFACE_TYPE] = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
211 attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
212 attribs[EGL_RED_SIZE] = 8;
213 attribs[EGL_GREEN_SIZE] = 8;
214 attribs[EGL_BLUE_SIZE] = 8;
215 attribs[EGL_ALPHA_SIZE] = 8;
216 wantedAttribute = EGL_NONE;
217 wantedAttributeValue = EGL_NONE;
218 } else {
219 // if no renderable type specified, fallback to a simplified query
220 wantedAttribute = EGL_NATIVE_VISUAL_ID;
221 wantedAttributeValue = format;
222 }
223
224 err = selectConfigForAttribute(display, attribs, wantedAttribute, wantedAttributeValue, config);
225 if (err == NO_ERROR) {
226 EGLint caveat;
227 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
228 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
229 }
230
231 return err;
232}
233
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700234std::unique_ptr<GLESRenderEngine> GLESRenderEngine::create(const RenderEngineCreationArgs& args) {
Peiyong Linf11f39b2018-09-05 14:37:41 -0700235 // initialize EGL for the default display
236 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
237 if (!eglInitialize(display, nullptr, nullptr)) {
238 LOG_ALWAYS_FATAL("failed to initialize EGL");
239 }
240
241 GLExtensions& extensions = GLExtensions::getInstance();
242 extensions.initWithEGLStrings(eglQueryStringImplementationANDROID(display, EGL_VERSION),
243 eglQueryStringImplementationANDROID(display, EGL_EXTENSIONS));
244
245 // The code assumes that ES2 or later is available if this extension is
246 // supported.
247 EGLConfig config = EGL_NO_CONFIG;
248 if (!extensions.hasNoConfigContext()) {
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700249 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700250 }
251
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700252 bool useContextPriority =
253 extensions.hasContextPriority() && args.contextPriority == ContextPriority::HIGH;
Peiyong Linfb530cf2018-12-15 05:07:38 +0000254 EGLContext protectedContext = EGL_NO_CONTEXT;
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700255 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Peiyong Linfb530cf2018-12-15 05:07:38 +0000256 protectedContext = createEglContext(display, config, nullptr, useContextPriority,
257 Protection::PROTECTED);
258 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
259 }
260
261 EGLContext ctxt = createEglContext(display, config, protectedContext, useContextPriority,
262 Protection::UNPROTECTED);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700263
264 // if can't create a GL context, we can only abort.
265 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
266
Peiyong Lina5e9f1b2018-11-27 22:49:37 -0800267 EGLSurface dummy = EGL_NO_SURFACE;
268 if (!extensions.hasSurfacelessContext()) {
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700269 dummy = createDummyEglPbufferSurface(display, config, args.pixelFormat,
270 Protection::UNPROTECTED);
Peiyong Lina5e9f1b2018-11-27 22:49:37 -0800271 LOG_ALWAYS_FATAL_IF(dummy == EGL_NO_SURFACE, "can't create dummy pbuffer");
Peiyong Linf11f39b2018-09-05 14:37:41 -0700272 }
Peiyong Linf11f39b2018-09-05 14:37:41 -0700273 EGLBoolean success = eglMakeCurrent(display, dummy, dummy, ctxt);
274 LOG_ALWAYS_FATAL_IF(!success, "can't make dummy pbuffer current");
Peiyong Linf11f39b2018-09-05 14:37:41 -0700275 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
276 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
277
Peiyong Linfb530cf2018-12-15 05:07:38 +0000278 EGLSurface protectedDummy = EGL_NO_SURFACE;
279 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700280 protectedDummy = createDummyEglPbufferSurface(display, config, args.pixelFormat,
281 Protection::PROTECTED);
Peiyong Linfb530cf2018-12-15 05:07:38 +0000282 ALOGE_IF(protectedDummy == EGL_NO_SURFACE, "can't create protected dummy pbuffer");
283 }
284
Peiyong Lina5e9f1b2018-11-27 22:49:37 -0800285 // now figure out what version of GL did we actually get
Peiyong Linf11f39b2018-09-05 14:37:41 -0700286 GlesVersion version = parseGlesVersion(extensions.getVersion());
287
Lucas Dupin453932d2020-02-03 20:42:25 -0800288 LOG_ALWAYS_FATAL_IF(args.supportsBackgroundBlur && version < GLES_VERSION_3_0,
289 "Blurs require OpenGL ES 3.0. Please unset ro.surface_flinger.supports_background_blur");
290
Peiyong Linf11f39b2018-09-05 14:37:41 -0700291 // initialize the renderer while GL is current
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800292 std::unique_ptr<GLESRenderEngine> engine;
Peiyong Linf11f39b2018-09-05 14:37:41 -0700293 switch (version) {
294 case GLES_VERSION_1_0:
295 case GLES_VERSION_1_1:
296 LOG_ALWAYS_FATAL("SurfaceFlinger requires OpenGL ES 2.0 minimum to run.");
297 break;
298 case GLES_VERSION_2_0:
299 case GLES_VERSION_3_0:
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700300 engine = std::make_unique<GLESRenderEngine>(args, display, config, ctxt, dummy,
301 protectedContext, protectedDummy);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700302 break;
303 }
Peiyong Linf11f39b2018-09-05 14:37:41 -0700304
305 ALOGI("OpenGL ES informations:");
306 ALOGI("vendor : %s", extensions.getVendor());
307 ALOGI("renderer : %s", extensions.getRenderer());
308 ALOGI("version : %s", extensions.getVersion());
309 ALOGI("extensions: %s", extensions.getExtensions());
310 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
311 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
312
Peiyong Linf11f39b2018-09-05 14:37:41 -0700313 return engine;
314}
315
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800316EGLConfig GLESRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
Peiyong Linf11f39b2018-09-05 14:37:41 -0700317 status_t err;
318 EGLConfig config;
319
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800320 // First try to get an ES3 config
321 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700322 if (err != NO_ERROR) {
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800323 // If ES3 fails, try to get an ES2 config
324 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700325 if (err != NO_ERROR) {
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800326 // If ES2 still doesn't work, probably because we're on the emulator.
Peiyong Linf11f39b2018-09-05 14:37:41 -0700327 // try a simplified query
328 ALOGW("no suitable EGLConfig found, trying a simpler query");
329 err = selectEGLConfig(display, format, 0, &config);
330 if (err != NO_ERROR) {
331 // this EGL is too lame for android
332 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
333 }
334 }
335 }
336
337 if (logConfig) {
338 // print some debugging info
339 EGLint r, g, b, a;
340 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
341 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
342 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
343 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
344 ALOGI("EGL information:");
345 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
346 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
347 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
348 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
349 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
350 }
351
352 return config;
353}
354
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700355GLESRenderEngine::GLESRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
356 EGLConfig config, EGLContext ctxt, EGLSurface dummy,
357 EGLContext protectedContext, EGLSurface protectedDummy)
358 : renderengine::impl::RenderEngine(args),
Alec Mouri0a9c7b82018-11-16 13:05:25 -0800359 mEGLDisplay(display),
360 mEGLConfig(config),
361 mEGLContext(ctxt),
362 mDummySurface(dummy),
Peiyong Linfb530cf2018-12-15 05:07:38 +0000363 mProtectedEGLContext(protectedContext),
364 mProtectedDummySurface(protectedDummy),
Chia-I Wu93e14df2018-06-04 10:10:17 -0700365 mVpWidth(0),
366 mVpHeight(0),
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700367 mFramebufferImageCacheSize(args.imageCacheSize),
368 mUseColorManagement(args.useColorManagement) {
Mathias Agopian3f844832013-08-07 21:24:32 -0700369 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
370 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
371
372 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
373 glPixelStorei(GL_PACK_ALIGNMENT, 4);
374
Peiyong Linfb530cf2018-12-15 05:07:38 +0000375 // Initialize protected EGL Context.
376 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
377 EGLBoolean success = eglMakeCurrent(display, mProtectedDummySurface, mProtectedDummySurface,
378 mProtectedEGLContext);
379 ALOGE_IF(!success, "can't make protected context current");
380 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
381 glPixelStorei(GL_PACK_ALIGNMENT, 4);
382 success = eglMakeCurrent(display, mDummySurface, mDummySurface, mEGLContext);
383 LOG_ALWAYS_FATAL_IF(!success, "can't make default context current");
384 }
385
Chia-I Wub027f802017-11-29 14:00:52 -0800386 const uint16_t protTexData[] = {0};
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 glGenTextures(1, &mProtectedTexName);
388 glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
389 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
390 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
391 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
392 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
Chia-I Wub027f802017-11-29 14:00:52 -0800393 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
Mathias Agopianff2ed702013-09-01 21:36:12 -0700394
Chia-I Wub027f802017-11-29 14:00:52 -0800395 // mColorBlindnessCorrection = M;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600396
Peiyong Lin13effd12018-07-24 17:01:47 -0700397 if (mUseColorManagement) {
Valerie Haueb8e0762018-11-06 10:10:42 -0800398 const ColorSpace srgb(ColorSpace::sRGB());
399 const ColorSpace displayP3(ColorSpace::DisplayP3());
400 const ColorSpace bt2020(ColorSpace::BT2020());
Peiyong Lina296b0c2018-04-30 16:55:29 -0700401
402 // no chromatic adaptation needed since all color spaces use D65 for their white points.
Peiyong Lin70b26ce2018-09-18 19:02:39 -0700403 mSrgbToXyz = mat4(srgb.getRGBtoXYZ());
404 mDisplayP3ToXyz = mat4(displayP3.getRGBtoXYZ());
405 mBt2020ToXyz = mat4(bt2020.getRGBtoXYZ());
Peiyong Lin9b03c732018-05-17 10:14:02 -0700406 mXyzToSrgb = mat4(srgb.getXYZtoRGB());
Peiyong Lina296b0c2018-04-30 16:55:29 -0700407 mXyzToDisplayP3 = mat4(displayP3.getXYZtoRGB());
408 mXyzToBt2020 = mat4(bt2020.getXYZtoRGB());
Valerie Haueb8e0762018-11-06 10:10:42 -0800409
410 // Compute sRGB to Display P3 and BT2020 transform matrix.
411 // NOTE: For now, we are limiting output wide color space support to
412 // Display-P3 and BT2020 only.
413 mSrgbToDisplayP3 = mXyzToDisplayP3 * mSrgbToXyz;
414 mSrgbToBt2020 = mXyzToBt2020 * mSrgbToXyz;
415
416 // Compute Display P3 to sRGB and BT2020 transform matrix.
417 mDisplayP3ToSrgb = mXyzToSrgb * mDisplayP3ToXyz;
418 mDisplayP3ToBt2020 = mXyzToBt2020 * mDisplayP3ToXyz;
419
420 // Compute BT2020 to sRGB and Display P3 transform matrix
421 mBt2020ToSrgb = mXyzToSrgb * mBt2020ToXyz;
422 mBt2020ToDisplayP3 = mXyzToDisplayP3 * mBt2020ToXyz;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600423 }
Alec Mouri554d06e2018-12-20 00:15:33 -0800424
425 char value[PROPERTY_VALUE_MAX];
426 property_get("debug.egl.traceGpuCompletion", value, "0");
427 if (atoi(value)) {
428 mTraceGpuCompletion = true;
429 mFlushTracer = std::make_unique<FlushTracer>(this);
430 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800431
432 if (args.supportsBackgroundBlur) {
433 char isGaussian[PROPERTY_VALUE_MAX];
Lucas Dupin453932d2020-02-03 20:42:25 -0800434 property_get("debug.sf.gaussianBlur", isGaussian, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800435 if (atoi(isGaussian)) {
436 mBlurFilter = new GaussianBlurFilter(*this);
437 } else {
Lucas Dupin453932d2020-02-03 20:42:25 -0800438 mBlurFilter = new KawaseBlurFilter(*this);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800439 }
440 checkErrors("BlurFilter creation");
441 }
442
Alec Mouri16a99402019-07-29 16:37:30 -0700443 mImageManager = std::make_unique<ImageManager>(this);
Alec Mouri820c7402019-01-23 13:02:39 -0800444 mDrawingBuffer = createFramebuffer();
Mathias Agopian3f844832013-08-07 21:24:32 -0700445}
446
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800447GLESRenderEngine::~GLESRenderEngine() {
Alec Mouri16a99402019-07-29 16:37:30 -0700448 // Destroy the image manager first.
449 mImageManager = nullptr;
Alec Mourid43ccab2019-03-13 12:23:45 -0700450 std::lock_guard<std::mutex> lock(mRenderingMutex);
451 unbindFrameBuffer(mDrawingBuffer.get());
452 mDrawingBuffer = nullptr;
453 while (!mFramebufferImageCache.empty()) {
454 EGLImageKHR expired = mFramebufferImageCache.front().second;
455 mFramebufferImageCache.pop_front();
456 eglDestroyImageKHR(mEGLDisplay, expired);
Ady Abrahama3b08ef2019-07-15 18:43:10 -0700457 DEBUG_EGL_IMAGE_TRACKER_DESTROY();
Alec Mourida4cf3b2019-02-12 15:33:01 -0800458 }
Alec Mourid43ccab2019-03-13 12:23:45 -0700459 mImageCache.clear();
Peiyong Linf11f39b2018-09-05 14:37:41 -0700460 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
461 eglTerminate(mEGLDisplay);
462}
Mathias Agopian3f844832013-08-07 21:24:32 -0700463
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800464std::unique_ptr<Framebuffer> GLESRenderEngine::createFramebuffer() {
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700465 return std::make_unique<GLFramebuffer>(*this);
466}
467
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800468std::unique_ptr<Image> GLESRenderEngine::createImage() {
Peiyong Linf1bada92018-08-29 09:39:31 -0700469 return std::make_unique<GLImage>(*this);
470}
471
Alec Mouri820c7402019-01-23 13:02:39 -0800472Framebuffer* GLESRenderEngine::getFramebufferForDrawing() {
473 return mDrawingBuffer.get();
474}
475
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800476void GLESRenderEngine::primeCache() const {
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700477 ProgramCache::getInstance().primeCache(mInProtectedContext ? mProtectedEGLContext : mEGLContext,
478 mArgs.useColorManagement,
479 mArgs.precacheToneMapperShaderOnly);
Peiyong Linf1bada92018-08-29 09:39:31 -0700480}
481
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800482base::unique_fd GLESRenderEngine::flush() {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000483 ATRACE_CALL();
Peiyong Lin60bedb52018-09-05 10:47:31 -0700484 if (!GLExtensions::getInstance().hasNativeFenceSync()) {
485 return base::unique_fd();
486 }
487
488 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
489 if (sync == EGL_NO_SYNC_KHR) {
490 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
491 return base::unique_fd();
492 }
493
494 // native fence fd will not be populated until flush() is done.
495 glFlush();
496
497 // get the fence fd
498 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
499 eglDestroySyncKHR(mEGLDisplay, sync);
500 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
501 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
502 }
503
Alec Mouri554d06e2018-12-20 00:15:33 -0800504 // Only trace if we have a valid fence, as current usage falls back to
505 // calling finish() if the fence fd is invalid.
506 if (CC_UNLIKELY(mTraceGpuCompletion && mFlushTracer) && fenceFd.get() >= 0) {
507 mFlushTracer->queueSync(eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, nullptr));
508 }
509
Peiyong Lin60bedb52018-09-05 10:47:31 -0700510 return fenceFd;
511}
512
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800513bool GLESRenderEngine::finish() {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000514 ATRACE_CALL();
Peiyong Lin60bedb52018-09-05 10:47:31 -0700515 if (!GLExtensions::getInstance().hasFenceSync()) {
516 ALOGW("no synchronization support");
517 return false;
518 }
519
520 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, nullptr);
521 if (sync == EGL_NO_SYNC_KHR) {
522 ALOGW("failed to create EGL fence sync: %#x", eglGetError());
523 return false;
524 }
525
Alec Mouri554d06e2018-12-20 00:15:33 -0800526 if (CC_UNLIKELY(mTraceGpuCompletion && mFlushTracer)) {
527 mFlushTracer->queueSync(eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, nullptr));
528 }
529
530 return waitSync(sync, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR);
531}
532
533bool GLESRenderEngine::waitSync(EGLSyncKHR sync, EGLint flags) {
534 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync, flags, 2000000000 /*2 sec*/);
Peiyong Lin60bedb52018-09-05 10:47:31 -0700535 EGLint error = eglGetError();
536 eglDestroySyncKHR(mEGLDisplay, sync);
537 if (result != EGL_CONDITION_SATISFIED_KHR) {
538 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
539 ALOGW("fence wait timed out");
540 } else {
541 ALOGW("error waiting on EGL fence: %#x", error);
542 }
543 return false;
544 }
545
546 return true;
547}
548
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800549bool GLESRenderEngine::waitFence(base::unique_fd fenceFd) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700550 if (!GLExtensions::getInstance().hasNativeFenceSync() ||
551 !GLExtensions::getInstance().hasWaitSync()) {
552 return false;
553 }
554
Peiyong Lin35a114c2019-04-25 14:37:13 -0700555 // release the fd and transfer the ownership to EGLSync
556 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
Peiyong Lin60bedb52018-09-05 10:47:31 -0700557 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
558 if (sync == EGL_NO_SYNC_KHR) {
559 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
560 return false;
561 }
562
Peiyong Lin60bedb52018-09-05 10:47:31 -0700563 // XXX: The spec draft is inconsistent as to whether this should return an
564 // EGLint or void. Ignore the return value for now, as it's not strictly
565 // needed.
566 eglWaitSyncKHR(mEGLDisplay, sync, 0);
567 EGLint error = eglGetError();
568 eglDestroySyncKHR(mEGLDisplay, sync);
569 if (error != EGL_SUCCESS) {
570 ALOGE("failed to wait for EGL native fence sync: %#x", error);
571 return false;
572 }
573
574 return true;
575}
576
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800577void GLESRenderEngine::clearWithColor(float red, float green, float blue, float alpha) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000578 ATRACE_CALL();
579 glDisable(GL_BLEND);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700580 glClearColor(red, green, blue, alpha);
581 glClear(GL_COLOR_BUFFER_BIT);
582}
583
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800584void GLESRenderEngine::fillRegionWithColor(const Region& region, float red, float green, float blue,
585 float alpha) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700586 size_t c;
587 Rect const* r = region.getArray(&c);
Vishnu Nair440992f2019-12-09 19:53:19 -0800588 Mesh mesh = Mesh::Builder()
589 .setPrimitive(Mesh::TRIANGLES)
590 .setVertices(c * 6 /* count */, 2 /* size */)
591 .build();
Peiyong Lin60bedb52018-09-05 10:47:31 -0700592 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
593 for (size_t i = 0; i < c; i++, r++) {
594 position[i * 6 + 0].x = r->left;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700595 position[i * 6 + 0].y = r->top;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700596 position[i * 6 + 1].x = r->left;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700597 position[i * 6 + 1].y = r->bottom;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700598 position[i * 6 + 2].x = r->right;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700599 position[i * 6 + 2].y = r->bottom;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700600 position[i * 6 + 3].x = r->left;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700601 position[i * 6 + 3].y = r->top;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700602 position[i * 6 + 4].x = r->right;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700603 position[i * 6 + 4].y = r->bottom;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700604 position[i * 6 + 5].x = r->right;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700605 position[i * 6 + 5].y = r->top;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700606 }
607 setupFillWithColor(red, green, blue, alpha);
608 drawMesh(mesh);
609}
610
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800611void GLESRenderEngine::setScissor(const Rect& region) {
Peiyong Lin1c097612019-03-22 16:21:46 -0700612 glScissor(region.left, region.top, region.getWidth(), region.getHeight());
Peiyong Lin60bedb52018-09-05 10:47:31 -0700613 glEnable(GL_SCISSOR_TEST);
614}
615
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800616void GLESRenderEngine::disableScissor() {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700617 glDisable(GL_SCISSOR_TEST);
618}
619
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800620void GLESRenderEngine::genTextures(size_t count, uint32_t* names) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700621 glGenTextures(count, names);
622}
623
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800624void GLESRenderEngine::deleteTextures(size_t count, uint32_t const* names) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700625 glDeleteTextures(count, names);
626}
627
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800628void GLESRenderEngine::bindExternalTextureImage(uint32_t texName, const Image& image) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000629 ATRACE_CALL();
Peiyong Linf1bada92018-08-29 09:39:31 -0700630 const GLImage& glImage = static_cast<const GLImage&>(image);
631 const GLenum target = GL_TEXTURE_EXTERNAL_OES;
632
633 glBindTexture(target, texName);
634 if (glImage.getEGLImage() != EGL_NO_IMAGE_KHR) {
Peiyong Lin46080ef2018-10-26 18:43:14 -0700635 glEGLImageTargetTexture2DOES(target, static_cast<GLeglImageOES>(glImage.getEGLImage()));
Peiyong Linf1bada92018-08-29 09:39:31 -0700636 }
Mathias Agopian3f844832013-08-07 21:24:32 -0700637}
638
Alec Mourid7b3a8b2019-03-21 11:44:18 -0700639status_t GLESRenderEngine::bindExternalTextureBuffer(uint32_t texName,
640 const sp<GraphicBuffer>& buffer,
641 const sp<Fence>& bufferFence) {
Alec Mouri16a99402019-07-29 16:37:30 -0700642 if (buffer == nullptr) {
643 return BAD_VALUE;
Alec Mourid7b3a8b2019-03-21 11:44:18 -0700644 }
645
Alec Mouri16a99402019-07-29 16:37:30 -0700646 ATRACE_CALL();
647
648 bool found = false;
649 {
650 std::lock_guard<std::mutex> lock(mRenderingMutex);
651 auto cachedImage = mImageCache.find(buffer->getId());
652 found = (cachedImage != mImageCache.end());
653 }
654
655 // If we couldn't find the image in the cache at this time, then either
656 // SurfaceFlinger messed up registering the buffer ahead of time or we got
657 // backed up creating other EGLImages.
658 if (!found) {
659 status_t cacheResult = mImageManager->cache(buffer);
660 if (cacheResult != NO_ERROR) {
661 return cacheResult;
662 }
663 }
664
665 // Whether or not we needed to cache, re-check mImageCache to make sure that
666 // there's an EGLImage. The current threading model guarantees that we don't
667 // destroy a cached image until it's really not needed anymore (i.e. this
668 // function should not be called), so the only possibility is that something
669 // terrible went wrong and we should just bind something and move on.
Alec Mouri3d7c5612019-07-09 13:51:37 -0700670 {
671 std::lock_guard<std::mutex> lock(mRenderingMutex);
672 auto cachedImage = mImageCache.find(buffer->getId());
Alec Mourid7b3a8b2019-03-21 11:44:18 -0700673
Alec Mouri3d7c5612019-07-09 13:51:37 -0700674 if (cachedImage == mImageCache.end()) {
675 // We failed creating the image if we got here, so bail out.
Alec Mouri16a99402019-07-29 16:37:30 -0700676 ALOGE("Failed to create an EGLImage when rendering");
Alec Mouri3d7c5612019-07-09 13:51:37 -0700677 bindExternalTextureImage(texName, *createImage());
678 return NO_INIT;
679 }
680
681 bindExternalTextureImage(texName, *cachedImage->second);
Alec Mouri0d5e1eb2018-11-10 20:40:12 -0800682 }
683
Alec Mouri0d5e1eb2018-11-10 20:40:12 -0800684 // Wait for the new buffer to be ready.
685 if (bufferFence != nullptr && bufferFence->isValid()) {
686 if (GLExtensions::getInstance().hasWaitSync()) {
687 base::unique_fd fenceFd(bufferFence->dup());
688 if (fenceFd == -1) {
689 ALOGE("error dup'ing fence fd: %d", errno);
690 return -errno;
691 }
692 if (!waitFence(std::move(fenceFd))) {
693 ALOGE("failed to wait on fence fd");
694 return UNKNOWN_ERROR;
695 }
696 } else {
697 status_t err = bufferFence->waitForever("RenderEngine::bindExternalTextureBuffer");
698 if (err != NO_ERROR) {
699 ALOGE("error waiting for fence: %d", err);
700 return err;
701 }
702 }
703 }
Alec Mouri539319f2018-12-19 17:56:23 -0800704
Alec Mouri0d5e1eb2018-11-10 20:40:12 -0800705 return NO_ERROR;
706}
707
Alec Mouri16a99402019-07-29 16:37:30 -0700708void GLESRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
709 mImageManager->cacheAsync(buffer, nullptr);
710}
711
712std::shared_ptr<ImageManager::Barrier> GLESRenderEngine::cacheExternalTextureBufferForTesting(
713 const sp<GraphicBuffer>& buffer) {
714 auto barrier = std::make_shared<ImageManager::Barrier>();
715 mImageManager->cacheAsync(buffer, barrier);
716 return barrier;
717}
718
719status_t GLESRenderEngine::cacheExternalTextureBufferInternal(const sp<GraphicBuffer>& buffer) {
Alec Mouri3d7c5612019-07-09 13:51:37 -0700720 if (buffer == nullptr) {
721 return BAD_VALUE;
722 }
723
724 {
725 std::lock_guard<std::mutex> lock(mRenderingMutex);
726 if (mImageCache.count(buffer->getId()) > 0) {
727 // If there's already an image then fail fast here.
728 return NO_ERROR;
729 }
730 }
731 ATRACE_CALL();
732
733 // Create the image without holding a lock so that we don't block anything.
734 std::unique_ptr<Image> newImage = createImage();
735
736 bool created = newImage->setNativeWindowBuffer(buffer->getNativeBuffer(),
737 buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
738 if (!created) {
739 ALOGE("Failed to create image. size=%ux%u st=%u usage=%#" PRIx64 " fmt=%d",
740 buffer->getWidth(), buffer->getHeight(), buffer->getStride(), buffer->getUsage(),
741 buffer->getPixelFormat());
742 return NO_INIT;
743 }
744
745 {
746 std::lock_guard<std::mutex> lock(mRenderingMutex);
747 if (mImageCache.count(buffer->getId()) > 0) {
748 // In theory it's possible for another thread to recache the image,
749 // so bail out if another thread won.
750 return NO_ERROR;
751 }
752 mImageCache.insert(std::make_pair(buffer->getId(), std::move(newImage)));
753 }
754
755 return NO_ERROR;
756}
757
Alec Mourib5c4f352019-02-19 19:46:38 -0800758void GLESRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Alec Mouri16a99402019-07-29 16:37:30 -0700759 mImageManager->releaseAsync(bufferId, nullptr);
760}
761
762std::shared_ptr<ImageManager::Barrier> GLESRenderEngine::unbindExternalTextureBufferForTesting(
763 uint64_t bufferId) {
764 auto barrier = std::make_shared<ImageManager::Barrier>();
765 mImageManager->releaseAsync(bufferId, barrier);
766 return barrier;
767}
768
769void GLESRenderEngine::unbindExternalTextureBufferInternal(uint64_t bufferId) {
770 std::unique_ptr<Image> image;
771 {
772 std::lock_guard<std::mutex> lock(mRenderingMutex);
773 const auto& cachedImage = mImageCache.find(bufferId);
774
775 if (cachedImage != mImageCache.end()) {
776 ALOGV("Destroying image for buffer: %" PRIu64, bufferId);
777 // Move the buffer out of cache first, so that we can destroy
778 // without holding the cache's lock.
779 image = std::move(cachedImage->second);
780 mImageCache.erase(bufferId);
781 return;
782 }
Alec Mouri539319f2018-12-19 17:56:23 -0800783 }
Alec Mourib5c4f352019-02-19 19:46:38 -0800784 ALOGV("Failed to find image for buffer: %" PRIu64, bufferId);
Alec Mouri539319f2018-12-19 17:56:23 -0800785}
786
Alec Mouri7c94edb2018-12-03 21:23:26 -0800787FloatRect GLESRenderEngine::setupLayerCropping(const LayerSettings& layer, Mesh& mesh) {
788 // Translate win by the rounded corners rect coordinates, to have all values in
789 // layer coordinate space.
790 FloatRect cropWin = layer.geometry.boundaries;
791 const FloatRect& roundedCornersCrop = layer.geometry.roundedCornersCrop;
792 cropWin.left -= roundedCornersCrop.left;
793 cropWin.right -= roundedCornersCrop.left;
794 cropWin.top -= roundedCornersCrop.top;
795 cropWin.bottom -= roundedCornersCrop.top;
796 Mesh::VertexArray<vec2> cropCoords(mesh.getCropCoordArray<vec2>());
797 cropCoords[0] = vec2(cropWin.left, cropWin.top);
798 cropCoords[1] = vec2(cropWin.left, cropWin.top + cropWin.getHeight());
799 cropCoords[2] = vec2(cropWin.right, cropWin.top + cropWin.getHeight());
800 cropCoords[3] = vec2(cropWin.right, cropWin.top);
801
802 setupCornerRadiusCropSize(roundedCornersCrop.getWidth(), roundedCornersCrop.getHeight());
803 return cropWin;
804}
805
Peiyong Lin1c097612019-03-22 16:21:46 -0700806void GLESRenderEngine::handleRoundedCorners(const DisplaySettings& display,
807 const LayerSettings& layer, const Mesh& mesh) {
808 // We separate the layer into 3 parts essentially, such that we only turn on blending for the
809 // top rectangle and the bottom rectangle, and turn off blending for the middle rectangle.
810 FloatRect bounds = layer.geometry.roundedCornersCrop;
Peiyong Linb1925962019-04-01 16:37:10 -0700811
812 // Firstly, we need to convert the coordination from layer native coordination space to
813 // device coordination space.
Peiyong Lin1c097612019-03-22 16:21:46 -0700814 const auto transformMatrix = display.globalTransform * layer.geometry.positionTransform;
815 const vec4 leftTopCoordinate(bounds.left, bounds.top, 1.0, 1.0);
816 const vec4 rightBottomCoordinate(bounds.right, bounds.bottom, 1.0, 1.0);
817 const vec4 leftTopCoordinateInBuffer = transformMatrix * leftTopCoordinate;
818 const vec4 rightBottomCoordinateInBuffer = transformMatrix * rightBottomCoordinate;
819 bounds = FloatRect(leftTopCoordinateInBuffer[0], leftTopCoordinateInBuffer[1],
820 rightBottomCoordinateInBuffer[0], rightBottomCoordinateInBuffer[1]);
Peiyong Lin1c097612019-03-22 16:21:46 -0700821
Peiyong Linb1925962019-04-01 16:37:10 -0700822 // Secondly, if the display is rotated, we need to undo the rotation on coordination and
823 // align the (left, top) and (right, bottom) coordination with the device coordination
824 // space.
825 switch (display.orientation) {
826 case ui::Transform::ROT_90:
827 std::swap(bounds.left, bounds.right);
828 break;
829 case ui::Transform::ROT_180:
830 std::swap(bounds.left, bounds.right);
831 std::swap(bounds.top, bounds.bottom);
832 break;
833 case ui::Transform::ROT_270:
834 std::swap(bounds.top, bounds.bottom);
835 break;
836 default:
837 break;
838 }
839
840 // Finally, we cut the layer into 3 parts, with top and bottom parts having rounded corners
841 // and the middle part without rounded corners.
842 const int32_t radius = ceil(layer.geometry.roundedCornersRadius);
Peiyong Lin1c097612019-03-22 16:21:46 -0700843 const Rect topRect(bounds.left, bounds.top, bounds.right, bounds.top + radius);
844 setScissor(topRect);
845 drawMesh(mesh);
846 const Rect bottomRect(bounds.left, bounds.bottom - radius, bounds.right, bounds.bottom);
847 setScissor(bottomRect);
848 drawMesh(mesh);
849
850 // The middle part of the layer can turn off blending.
Lucas Dupinc9691d52019-09-26 13:46:04 -0700851 if (topRect.bottom < bottomRect.top) {
852 const Rect middleRect(bounds.left, bounds.top + radius, bounds.right,
853 bounds.bottom - radius);
854 setScissor(middleRect);
855 mState.cornerRadius = 0.0;
856 disableBlending();
857 drawMesh(mesh);
858 }
Peiyong Lin1c097612019-03-22 16:21:46 -0700859 disableScissor();
860}
861
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800862status_t GLESRenderEngine::bindFrameBuffer(Framebuffer* framebuffer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000863 ATRACE_CALL();
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700864 GLFramebuffer* glFramebuffer = static_cast<GLFramebuffer*>(framebuffer);
865 EGLImageKHR eglImage = glFramebuffer->getEGLImage();
866 uint32_t textureName = glFramebuffer->getTextureName();
867 uint32_t framebufferName = glFramebuffer->getFramebufferName();
868
869 // Bind the texture and turn our EGLImage into a texture
870 glBindTexture(GL_TEXTURE_2D, textureName);
871 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)eglImage);
872
873 // Bind the Framebuffer to render into
874 glBindFramebuffer(GL_FRAMEBUFFER, framebufferName);
Peiyong Lin46080ef2018-10-26 18:43:14 -0700875 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureName, 0);
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700876
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700877 uint32_t glStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
Peiyong Lin46080ef2018-10-26 18:43:14 -0700878 ALOGE_IF(glStatus != GL_FRAMEBUFFER_COMPLETE_OES, "glCheckFramebufferStatusOES error %d",
879 glStatus);
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700880
881 return glStatus == GL_FRAMEBUFFER_COMPLETE_OES ? NO_ERROR : BAD_VALUE;
882}
883
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800884void GLESRenderEngine::unbindFrameBuffer(Framebuffer* /* framebuffer */) {
Alec Mouri820c7402019-01-23 13:02:39 -0800885 ATRACE_CALL();
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700886
887 // back to main framebuffer
888 glBindFramebuffer(GL_FRAMEBUFFER, 0);
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700889}
890
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800891void GLESRenderEngine::checkErrors() const {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800892 checkErrors(nullptr);
893}
894
895void GLESRenderEngine::checkErrors(const char* tag) const {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700896 do {
897 // there could be more than one error flag
898 GLenum error = glGetError();
899 if (error == GL_NO_ERROR) break;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800900 if (tag == nullptr) {
901 ALOGE("GL error 0x%04x", int(error));
902 } else {
903 ALOGE("GL error: %s -> 0x%04x", tag, int(error));
904 }
Peiyong Lin60bedb52018-09-05 10:47:31 -0700905 } while (true);
906}
907
Peiyong Linfb530cf2018-12-15 05:07:38 +0000908bool GLESRenderEngine::supportsProtectedContent() const {
909 return mProtectedEGLContext != EGL_NO_CONTEXT;
910}
911
912bool GLESRenderEngine::useProtectedContext(bool useProtectedContext) {
913 if (useProtectedContext == mInProtectedContext) {
914 return true;
915 }
916 if (useProtectedContext && mProtectedEGLContext == EGL_NO_CONTEXT) {
917 return false;
918 }
919 const EGLSurface surface = useProtectedContext ? mProtectedDummySurface : mDummySurface;
920 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
921 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
922 if (success) {
923 mInProtectedContext = useProtectedContext;
924 }
925 return success;
926}
Alec Mourida4cf3b2019-02-12 15:33:01 -0800927EGLImageKHR GLESRenderEngine::createFramebufferImageIfNeeded(ANativeWindowBuffer* nativeBuffer,
Alec Mourife0d72b2019-03-21 14:05:56 -0700928 bool isProtected,
929 bool useFramebufferCache) {
Alec Mourida4cf3b2019-02-12 15:33:01 -0800930 sp<GraphicBuffer> graphicBuffer = GraphicBuffer::from(nativeBuffer);
Alec Mourife0d72b2019-03-21 14:05:56 -0700931 if (useFramebufferCache) {
Alec Mourief44c2d2019-07-15 15:27:22 -0700932 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
Alec Mourife0d72b2019-03-21 14:05:56 -0700933 for (const auto& image : mFramebufferImageCache) {
934 if (image.first == graphicBuffer->getId()) {
935 return image.second;
936 }
Alec Mourida4cf3b2019-02-12 15:33:01 -0800937 }
938 }
939 EGLint attributes[] = {
940 isProtected ? EGL_PROTECTED_CONTENT_EXT : EGL_NONE,
941 isProtected ? EGL_TRUE : EGL_NONE,
942 EGL_NONE,
943 };
944 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
945 nativeBuffer, attributes);
Alec Mourife0d72b2019-03-21 14:05:56 -0700946 if (useFramebufferCache) {
947 if (image != EGL_NO_IMAGE_KHR) {
Alec Mourief44c2d2019-07-15 15:27:22 -0700948 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
Alec Mourife0d72b2019-03-21 14:05:56 -0700949 if (mFramebufferImageCache.size() >= mFramebufferImageCacheSize) {
950 EGLImageKHR expired = mFramebufferImageCache.front().second;
951 mFramebufferImageCache.pop_front();
952 eglDestroyImageKHR(mEGLDisplay, expired);
Ady Abrahama3b08ef2019-07-15 18:43:10 -0700953 DEBUG_EGL_IMAGE_TRACKER_DESTROY();
Alec Mourife0d72b2019-03-21 14:05:56 -0700954 }
955 mFramebufferImageCache.push_back({graphicBuffer->getId(), image});
Alec Mourida4cf3b2019-02-12 15:33:01 -0800956 }
Alec Mourida4cf3b2019-02-12 15:33:01 -0800957 }
Ady Abrahama3b08ef2019-07-15 18:43:10 -0700958
959 if (image != EGL_NO_IMAGE_KHR) {
960 DEBUG_EGL_IMAGE_TRACKER_CREATE();
961 }
Alec Mourida4cf3b2019-02-12 15:33:01 -0800962 return image;
963}
Peiyong Linfb530cf2018-12-15 05:07:38 +0000964
Alec Mouri1089aed2018-10-25 21:33:57 -0700965status_t GLESRenderEngine::drawLayers(const DisplaySettings& display,
Vishnu Nair9b079a22020-01-21 14:36:08 -0800966 const std::vector<const LayerSettings*>& layers,
Alec Mouri1089aed2018-10-25 21:33:57 -0700967 ANativeWindowBuffer* const buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -0700968 const bool useFramebufferCache, base::unique_fd&& bufferFence,
969 base::unique_fd* drawFence) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000970 ATRACE_CALL();
Alec Mouri1089aed2018-10-25 21:33:57 -0700971 if (layers.empty()) {
972 ALOGV("Drawing empty layer stack");
973 return NO_ERROR;
974 }
975
Alec Mouri6338c9d2019-02-07 16:57:51 -0800976 if (bufferFence.get() >= 0 && !waitFence(std::move(bufferFence))) {
977 ATRACE_NAME("Waiting before draw");
978 sync_wait(bufferFence.get(), -1);
979 }
980
Alec Mourid43ccab2019-03-13 12:23:45 -0700981 if (buffer == nullptr) {
982 ALOGE("No output buffer provided. Aborting GPU composition.");
983 return BAD_VALUE;
984 }
985
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800986 std::unique_ptr<BindNativeBufferAsFramebuffer> fbo;
987 // Let's find the topmost layer requesting background blur (if any.)
988 // Blurs in multiple layers are not supported, given the cost of the shader.
989 const LayerSettings* blurLayer = nullptr;
990 if (CC_LIKELY(mBlurFilter != nullptr)) {
Vishnu Nair9b079a22020-01-21 14:36:08 -0800991 for (auto const layer : layers) {
992 if (layer->backgroundBlurRadius > 0) {
993 blurLayer = layer;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800994 }
995 }
996 }
Alec Mouri1089aed2018-10-25 21:33:57 -0700997
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800998 if (blurLayer == nullptr) {
999 fbo = std::make_unique<BindNativeBufferAsFramebuffer>(*this, buffer, useFramebufferCache);
1000 if (fbo->getStatus() != NO_ERROR) {
1001 ALOGE("Failed to bind framebuffer! Aborting GPU composition for buffer (%p).",
1002 buffer->handle);
1003 checkErrors();
1004 return fbo->getStatus();
1005 }
1006 setViewportAndProjection(display.physicalDisplay, display.clip);
1007 } else {
1008 setViewportAndProjection(display.physicalDisplay, display.clip);
Lucas Dupinf82ed8f2020-01-17 12:11:07 -08001009 auto status = mBlurFilter->setAsDrawTarget(display, blurLayer->backgroundBlurRadius);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001010 if (status != NO_ERROR) {
1011 ALOGE("Failed to prepare blur filter! Aborting GPU composition for buffer (%p).",
1012 buffer->handle);
1013 checkErrors();
1014 return status;
1015 }
Alec Mourif0497272019-03-11 15:53:11 -07001016 }
Alec Mouri3d7c5612019-07-09 13:51:37 -07001017
1018 // clear the entire buffer, sometimes when we reuse buffers we'd persist
1019 // ghost images otherwise.
1020 // we also require a full transparent framebuffer for overlays. This is
1021 // probably not quite efficient on all GPUs, since we could filter out
1022 // opaque layers.
1023 clearWithColor(0.0, 0.0, 0.0, 0.0);
1024
Alec Mouri3d7c5612019-07-09 13:51:37 -07001025 setOutputDataSpace(display.outputDataspace);
1026 setDisplayMaxLuminance(display.maxLuminance);
1027
1028 mat4 projectionMatrix = mState.projectionMatrix * display.globalTransform;
1029 mState.projectionMatrix = projectionMatrix;
1030 if (!display.clearRegion.isEmpty()) {
1031 glDisable(GL_BLEND);
1032 fillRegionWithColor(display.clearRegion, 0.0, 0.0, 0.0, 1.0);
1033 }
1034
Vishnu Nair440992f2019-12-09 19:53:19 -08001035 Mesh mesh = Mesh::Builder()
1036 .setPrimitive(Mesh::TRIANGLE_FAN)
1037 .setVertices(4 /* count */, 2 /* size */)
1038 .setTexCoords(2 /* size */)
1039 .setCropCoords(2 /* size */)
1040 .build();
Vishnu Nair9b079a22020-01-21 14:36:08 -08001041 for (auto const layer : layers) {
1042 if (blurLayer == layer) {
Lucas Dupinf82ed8f2020-01-17 12:11:07 -08001043 auto status = mBlurFilter->prepare();
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001044 if (status != NO_ERROR) {
1045 ALOGE("Failed to render blur effect! Aborting GPU composition for buffer (%p).",
1046 buffer->handle);
1047 checkErrors("Can't render first blur pass");
1048 return status;
1049 }
1050
1051 fbo = std::make_unique<BindNativeBufferAsFramebuffer>(*this, buffer,
1052 useFramebufferCache);
1053 status = fbo->getStatus();
1054 if (status != NO_ERROR) {
1055 ALOGE("Failed to bind framebuffer! Aborting GPU composition for buffer (%p).",
1056 buffer->handle);
1057 checkErrors("Can't bind native framebuffer");
1058 return status;
1059 }
1060 setViewportAndProjection(display.physicalDisplay, display.clip);
1061
1062 status = mBlurFilter->render();
1063 if (status != NO_ERROR) {
1064 ALOGE("Failed to render blur effect! Aborting GPU composition for buffer (%p).",
1065 buffer->handle);
1066 checkErrors("Can't render blur filter");
1067 return status;
1068 }
1069 }
1070
Vishnu Nair9b079a22020-01-21 14:36:08 -08001071 mState.maxMasteringLuminance = layer->source.buffer.maxMasteringLuminance;
1072 mState.maxContentLuminance = layer->source.buffer.maxContentLuminance;
1073 mState.projectionMatrix = projectionMatrix * layer->geometry.positionTransform;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001074
Vishnu Nair9b079a22020-01-21 14:36:08 -08001075 const FloatRect bounds = layer->geometry.boundaries;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001076 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1077 position[0] = vec2(bounds.left, bounds.top);
1078 position[1] = vec2(bounds.left, bounds.bottom);
1079 position[2] = vec2(bounds.right, bounds.bottom);
1080 position[3] = vec2(bounds.right, bounds.top);
1081
Vishnu Nair9b079a22020-01-21 14:36:08 -08001082 setupLayerCropping(*layer, mesh);
1083 setColorTransform(display.colorTransform * layer->colorTransform);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001084
1085 bool usePremultipliedAlpha = true;
1086 bool disableTexture = true;
1087 bool isOpaque = false;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001088 if (layer->source.buffer.buffer != nullptr) {
Alec Mouri3d7c5612019-07-09 13:51:37 -07001089 disableTexture = false;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001090 isOpaque = layer->source.buffer.isOpaque;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001091
Vishnu Nair9b079a22020-01-21 14:36:08 -08001092 sp<GraphicBuffer> gBuf = layer->source.buffer.buffer;
1093 bindExternalTextureBuffer(layer->source.buffer.textureName, gBuf,
1094 layer->source.buffer.fence);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001095
Vishnu Nair9b079a22020-01-21 14:36:08 -08001096 usePremultipliedAlpha = layer->source.buffer.usePremultipliedAlpha;
1097 Texture texture(Texture::TEXTURE_EXTERNAL, layer->source.buffer.textureName);
1098 mat4 texMatrix = layer->source.buffer.textureTransform;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001099
1100 texture.setMatrix(texMatrix.asArray());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001101 texture.setFiltering(layer->source.buffer.useTextureFiltering);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001102
1103 texture.setDimensions(gBuf->getWidth(), gBuf->getHeight());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001104 setSourceY410BT2020(layer->source.buffer.isY410BT2020);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001105
1106 renderengine::Mesh::VertexArray<vec2> texCoords(mesh.getTexCoordArray<vec2>());
1107 texCoords[0] = vec2(0.0, 0.0);
1108 texCoords[1] = vec2(0.0, 1.0);
1109 texCoords[2] = vec2(1.0, 1.0);
1110 texCoords[3] = vec2(1.0, 0.0);
1111 setupLayerTexturing(texture);
1112 }
1113
Vishnu Nair9b079a22020-01-21 14:36:08 -08001114 const half3 solidColor = layer->source.solidColor;
1115 const half4 color = half4(solidColor.r, solidColor.g, solidColor.b, layer->alpha);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001116 // Buffer sources will have a black solid color ignored in the shader,
1117 // so in that scenario the solid color passed here is arbitrary.
1118 setupLayerBlending(usePremultipliedAlpha, isOpaque, disableTexture, color,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001119 layer->geometry.roundedCornersRadius);
1120 if (layer->disableBlending) {
Alec Mouri3d7c5612019-07-09 13:51:37 -07001121 glDisable(GL_BLEND);
1122 }
Vishnu Nair9b079a22020-01-21 14:36:08 -08001123 setSourceDataSpace(layer->sourceDataspace);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001124
Vishnu Nair9b079a22020-01-21 14:36:08 -08001125 if (layer->shadow.length > 0.0f) {
1126 handleShadow(layer->geometry.boundaries, layer->geometry.roundedCornersRadius,
1127 layer->shadow);
Vishnu Nair440992f2019-12-09 19:53:19 -08001128 }
Alec Mouri3d7c5612019-07-09 13:51:37 -07001129 // We only want to do a special handling for rounded corners when having rounded corners
1130 // is the only reason it needs to turn on blending, otherwise, we handle it like the
1131 // usual way since it needs to turn on blending anyway.
Vishnu Nair9b079a22020-01-21 14:36:08 -08001132 else if (layer->geometry.roundedCornersRadius > 0.0 && color.a >= 1.0f && isOpaque) {
1133 handleRoundedCorners(display, *layer, mesh);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001134 } else {
1135 drawMesh(mesh);
1136 }
1137
1138 // Cleanup if there's a buffer source
Vishnu Nair9b079a22020-01-21 14:36:08 -08001139 if (layer->source.buffer.buffer != nullptr) {
Alec Mouri3d7c5612019-07-09 13:51:37 -07001140 disableBlending();
1141 setSourceY410BT2020(false);
1142 disableTexturing();
1143 }
1144 }
1145
1146 if (drawFence != nullptr) {
1147 *drawFence = flush();
1148 }
1149 // If flush failed or we don't support native fences, we need to force the
1150 // gl command stream to be executed.
1151 if (drawFence == nullptr || drawFence->get() < 0) {
1152 bool success = finish();
1153 if (!success) {
1154 ALOGE("Failed to flush RenderEngine commands");
1155 checkErrors();
1156 // Chances are, something illegal happened (either the caller passed
1157 // us bad parameters, or we messed up our shader generation).
1158 return INVALID_OPERATION;
1159 }
1160 }
1161
1162 checkErrors();
Alec Mouri6e57f682018-09-29 20:45:08 -07001163 return NO_ERROR;
1164}
1165
Alec Mouri1089aed2018-10-25 21:33:57 -07001166void GLESRenderEngine::setViewportAndProjection(Rect viewport, Rect clip) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001167 ATRACE_CALL();
Alec Mouri1089aed2018-10-25 21:33:57 -07001168 mVpWidth = viewport.getWidth();
1169 mVpHeight = viewport.getHeight();
1170
1171 // We pass the the top left corner instead of the bottom left corner,
1172 // because since we're rendering off-screen first.
1173 glViewport(viewport.left, viewport.top, mVpWidth, mVpHeight);
1174
1175 mState.projectionMatrix = mat4::ortho(clip.left, clip.right, clip.top, clip.bottom, 0, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001176}
1177
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001178void GLESRenderEngine::setupLayerBlending(bool premultipliedAlpha, bool opaque, bool disableTexture,
1179 const half4& color, float cornerRadius) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001180 mState.isPremultipliedAlpha = premultipliedAlpha;
1181 mState.isOpaque = opaque;
1182 mState.color = color;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001183 mState.cornerRadius = cornerRadius;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184
chaviw13fdc492017-06-27 12:40:18 -07001185 if (disableTexture) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001186 mState.textureEnabled = false;
chaviw13fdc492017-06-27 12:40:18 -07001187 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001188
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001189 if (color.a < 1.0f || !opaque || cornerRadius > 0.0f) {
Mathias Agopian3f844832013-08-07 21:24:32 -07001190 glEnable(GL_BLEND);
1191 glBlendFunc(premultipliedAlpha ? GL_ONE : GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1192 } else {
1193 glDisable(GL_BLEND);
1194 }
1195}
1196
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001197void GLESRenderEngine::setSourceY410BT2020(bool enable) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001198 mState.isY410BT2020 = enable;
Chia-I Wu131d3762018-01-11 14:35:27 -08001199}
1200
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001201void GLESRenderEngine::setSourceDataSpace(Dataspace source) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08001202 mDataSpace = source;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001203}
1204
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001205void GLESRenderEngine::setOutputDataSpace(Dataspace dataspace) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08001206 mOutputDataSpace = dataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001207}
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001208
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001209void GLESRenderEngine::setDisplayMaxLuminance(const float maxLuminance) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001210 mState.displayMaxLuminance = maxLuminance;
Peiyong Linfb069302018-04-25 14:34:31 -07001211}
1212
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001213void GLESRenderEngine::setupLayerTexturing(const Texture& texture) {
Mathias Agopian49457ac2013-08-14 18:20:17 -07001214 GLuint target = texture.getTextureTarget();
1215 glBindTexture(target, texture.getTextureName());
Mathias Agopian3f844832013-08-07 21:24:32 -07001216 GLenum filter = GL_NEAREST;
Mathias Agopian49457ac2013-08-14 18:20:17 -07001217 if (texture.getFiltering()) {
Mathias Agopian3f844832013-08-07 21:24:32 -07001218 filter = GL_LINEAR;
1219 }
Mathias Agopian49457ac2013-08-14 18:20:17 -07001220 glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1221 glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1222 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
1223 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);
Mathias Agopian3f844832013-08-07 21:24:32 -07001224
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001225 mState.texture = texture;
1226 mState.textureEnabled = true;
Mathias Agopian3f844832013-08-07 21:24:32 -07001227}
1228
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001229void GLESRenderEngine::setColorTransform(const mat4& colorTransform) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001230 mState.colorMatrix = colorTransform;
Dan Stozaf0087992014-10-20 15:46:09 -07001231}
1232
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001233void GLESRenderEngine::disableTexturing() {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001234 mState.textureEnabled = false;
Mathias Agopian3f844832013-08-07 21:24:32 -07001235}
1236
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001237void GLESRenderEngine::disableBlending() {
Mathias Agopian3f844832013-08-07 21:24:32 -07001238 glDisable(GL_BLEND);
1239}
1240
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001241void GLESRenderEngine::setupFillWithColor(float r, float g, float b, float a) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001242 mState.isPremultipliedAlpha = true;
1243 mState.isOpaque = false;
1244 mState.color = half4(r, g, b, a);
1245 mState.textureEnabled = false;
Mathias Agopian3f844832013-08-07 21:24:32 -07001246 glDisable(GL_BLEND);
Mathias Agopian3f844832013-08-07 21:24:32 -07001247}
1248
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001249void GLESRenderEngine::setupCornerRadiusCropSize(float width, float height) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001250 mState.cropSize = half2(width, height);
1251}
1252
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001253void GLESRenderEngine::drawMesh(const Mesh& mesh) {
Dan Stoza2713c302018-03-28 17:07:36 -07001254 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07001255 if (mesh.getTexCoordsSize()) {
1256 glEnableVertexAttribArray(Program::texCoords);
Chia-I Wub027f802017-11-29 14:00:52 -08001257 glVertexAttribPointer(Program::texCoords, mesh.getTexCoordsSize(), GL_FLOAT, GL_FALSE,
1258 mesh.getByteStride(), mesh.getTexCoords());
Mathias Agopian3f844832013-08-07 21:24:32 -07001259 }
1260
Chia-I Wub027f802017-11-29 14:00:52 -08001261 glVertexAttribPointer(Program::position, mesh.getVertexSize(), GL_FLOAT, GL_FALSE,
1262 mesh.getByteStride(), mesh.getPositions());
Mathias Agopian3f844832013-08-07 21:24:32 -07001263
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001264 if (mState.cornerRadius > 0.0f) {
1265 glEnableVertexAttribArray(Program::cropCoords);
1266 glVertexAttribPointer(Program::cropCoords, mesh.getVertexSize(), GL_FLOAT, GL_FALSE,
1267 mesh.getByteStride(), mesh.getCropCoords());
1268 }
1269
Vishnu Nair440992f2019-12-09 19:53:19 -08001270 if (mState.drawShadows) {
1271 glEnableVertexAttribArray(Program::shadowColor);
1272 glVertexAttribPointer(Program::shadowColor, mesh.getShadowColorSize(), GL_FLOAT, GL_FALSE,
1273 mesh.getByteStride(), mesh.getShadowColor());
1274
1275 glEnableVertexAttribArray(Program::shadowParams);
1276 glVertexAttribPointer(Program::shadowParams, mesh.getShadowParamsSize(), GL_FLOAT, GL_FALSE,
1277 mesh.getByteStride(), mesh.getShadowParams());
1278 }
1279
1280 Description managedState = mState;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001281 // By default, DISPLAY_P3 is the only supported wide color output. However,
1282 // when HDR content is present, hardware composer may be able to handle
1283 // BT2020 data space, in that case, the output data space is set to be
1284 // BT2020_HLG or BT2020_PQ respectively. In GPU fall back we need
1285 // to respect this and convert non-HDR content to HDR format.
Peiyong Lin13effd12018-07-24 17:01:47 -07001286 if (mUseColorManagement) {
Peiyong Lina296b0c2018-04-30 16:55:29 -07001287 Dataspace inputStandard = static_cast<Dataspace>(mDataSpace & Dataspace::STANDARD_MASK);
1288 Dataspace inputTransfer = static_cast<Dataspace>(mDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lin46080ef2018-10-26 18:43:14 -07001289 Dataspace outputStandard =
1290 static_cast<Dataspace>(mOutputDataSpace & Dataspace::STANDARD_MASK);
1291 Dataspace outputTransfer =
1292 static_cast<Dataspace>(mOutputDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001293 bool needsXYZConversion = needsXYZTransformMatrix();
1294
Valerie Haueb8e0762018-11-06 10:10:42 -08001295 // NOTE: if the input standard of the input dataspace is not STANDARD_DCI_P3 or
1296 // STANDARD_BT2020, it will be treated as STANDARD_BT709
1297 if (inputStandard != Dataspace::STANDARD_DCI_P3 &&
1298 inputStandard != Dataspace::STANDARD_BT2020) {
1299 inputStandard = Dataspace::STANDARD_BT709;
1300 }
1301
Peiyong Lina296b0c2018-04-30 16:55:29 -07001302 if (needsXYZConversion) {
1303 // The supported input color spaces are standard RGB, Display P3 and BT2020.
1304 switch (inputStandard) {
1305 case Dataspace::STANDARD_DCI_P3:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001306 managedState.inputTransformMatrix = mDisplayP3ToXyz;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001307 break;
1308 case Dataspace::STANDARD_BT2020:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001309 managedState.inputTransformMatrix = mBt2020ToXyz;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001310 break;
1311 default:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001312 managedState.inputTransformMatrix = mSrgbToXyz;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001313 break;
1314 }
1315
Peiyong Lin9b03c732018-05-17 10:14:02 -07001316 // The supported output color spaces are BT2020, Display P3 and standard RGB.
Peiyong Lina296b0c2018-04-30 16:55:29 -07001317 switch (outputStandard) {
1318 case Dataspace::STANDARD_BT2020:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001319 managedState.outputTransformMatrix = mXyzToBt2020;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001320 break;
Peiyong Lin9b03c732018-05-17 10:14:02 -07001321 case Dataspace::STANDARD_DCI_P3:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001322 managedState.outputTransformMatrix = mXyzToDisplayP3;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001323 break;
Peiyong Lin9b03c732018-05-17 10:14:02 -07001324 default:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001325 managedState.outputTransformMatrix = mXyzToSrgb;
Peiyong Lin9b03c732018-05-17 10:14:02 -07001326 break;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001327 }
1328 } else if (inputStandard != outputStandard) {
1329 // At this point, the input data space and output data space could be both
1330 // HDR data spaces, but they match each other, we do nothing in this case.
1331 // In addition to the case above, the input data space could be
1332 // - scRGB linear
1333 // - scRGB non-linear
1334 // - sRGB
1335 // - Display P3
Valerie Haueb8e0762018-11-06 10:10:42 -08001336 // - BT2020
Peiyong Lina296b0c2018-04-30 16:55:29 -07001337 // The output data spaces could be
1338 // - sRGB
1339 // - Display P3
Valerie Haueb8e0762018-11-06 10:10:42 -08001340 // - BT2020
1341 switch (outputStandard) {
1342 case Dataspace::STANDARD_BT2020:
1343 if (inputStandard == Dataspace::STANDARD_BT709) {
1344 managedState.outputTransformMatrix = mSrgbToBt2020;
1345 } else if (inputStandard == Dataspace::STANDARD_DCI_P3) {
1346 managedState.outputTransformMatrix = mDisplayP3ToBt2020;
1347 }
1348 break;
1349 case Dataspace::STANDARD_DCI_P3:
1350 if (inputStandard == Dataspace::STANDARD_BT709) {
1351 managedState.outputTransformMatrix = mSrgbToDisplayP3;
1352 } else if (inputStandard == Dataspace::STANDARD_BT2020) {
1353 managedState.outputTransformMatrix = mBt2020ToDisplayP3;
1354 }
1355 break;
1356 default:
1357 if (inputStandard == Dataspace::STANDARD_DCI_P3) {
1358 managedState.outputTransformMatrix = mDisplayP3ToSrgb;
1359 } else if (inputStandard == Dataspace::STANDARD_BT2020) {
1360 managedState.outputTransformMatrix = mBt2020ToSrgb;
1361 }
1362 break;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001363 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001364 }
Peiyong Lina296b0c2018-04-30 16:55:29 -07001365
1366 // we need to convert the RGB value to linear space and convert it back when:
1367 // - there is a color matrix that is not an identity matrix, or
1368 // - there is an output transform matrix that is not an identity matrix, or
1369 // - the input transfer function doesn't match the output transfer function.
Peiyong Lin13effd12018-07-24 17:01:47 -07001370 if (managedState.hasColorMatrix() || managedState.hasOutputTransformMatrix() ||
Chia-I Wud49d6692018-06-27 07:17:41 +08001371 inputTransfer != outputTransfer) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001372 managedState.inputTransferFunction =
Peiyong Lin46080ef2018-10-26 18:43:14 -07001373 Description::dataSpaceToTransferFunction(inputTransfer);
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001374 managedState.outputTransferFunction =
Peiyong Lin46080ef2018-10-26 18:43:14 -07001375 Description::dataSpaceToTransferFunction(outputTransfer);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001376 }
Vishnu Nair440992f2019-12-09 19:53:19 -08001377 }
Peiyong Lina296b0c2018-04-30 16:55:29 -07001378
Vishnu Nair440992f2019-12-09 19:53:19 -08001379 ProgramCache::getInstance().useProgram(mInProtectedContext ? mProtectedEGLContext : mEGLContext,
1380 managedState);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001381
Vishnu Nair440992f2019-12-09 19:53:19 -08001382 if (mState.drawShadows) {
1383 glDrawElements(mesh.getPrimitive(), mesh.getIndexCount(), GL_UNSIGNED_SHORT,
1384 mesh.getIndices());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001385 } else {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001386 glDrawArrays(mesh.getPrimitive(), 0, mesh.getVertexCount());
1387 }
Mathias Agopian3f844832013-08-07 21:24:32 -07001388
Vishnu Nair440992f2019-12-09 19:53:19 -08001389 if (mUseColorManagement && outputDebugPPMs) {
1390 static uint64_t managedColorFrameCount = 0;
1391 std::ostringstream out;
1392 out << "/data/texture_out" << managedColorFrameCount++;
1393 writePPM(out.str().c_str(), mVpWidth, mVpHeight);
1394 }
1395
Mathias Agopian3f844832013-08-07 21:24:32 -07001396 if (mesh.getTexCoordsSize()) {
1397 glDisableVertexAttribArray(Program::texCoords);
1398 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001399
1400 if (mState.cornerRadius > 0.0f) {
1401 glDisableVertexAttribArray(Program::cropCoords);
1402 }
Vishnu Nair440992f2019-12-09 19:53:19 -08001403
1404 if (mState.drawShadows) {
1405 glDisableVertexAttribArray(Program::shadowColor);
1406 glDisableVertexAttribArray(Program::shadowParams);
1407 }
Mathias Agopian3f844832013-08-07 21:24:32 -07001408}
1409
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001410size_t GLESRenderEngine::getMaxTextureSize() const {
Peiyong Linf1bada92018-08-29 09:39:31 -07001411 return mMaxTextureSize;
1412}
1413
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001414size_t GLESRenderEngine::getMaxViewportDims() const {
Peiyong Linf1bada92018-08-29 09:39:31 -07001415 return mMaxViewportDims[0] < mMaxViewportDims[1] ? mMaxViewportDims[0] : mMaxViewportDims[1];
1416}
1417
Yiwei Zhang5434a782018-12-05 18:06:32 -08001418void GLESRenderEngine::dump(std::string& result) {
Peiyong Linf11f39b2018-09-05 14:37:41 -07001419 const GLExtensions& extensions = GLExtensions::getInstance();
Peiyong Linfb530cf2018-12-15 05:07:38 +00001420 ProgramCache& cache = ProgramCache::getInstance();
Peiyong Linf11f39b2018-09-05 14:37:41 -07001421
Yiwei Zhang5434a782018-12-05 18:06:32 -08001422 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1423 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
Yiwei Zhang5434a782018-12-05 18:06:32 -08001424 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1425 extensions.getVersion());
1426 StringAppendF(&result, "%s\n", extensions.getExtensions());
Peiyong Line62c5cb2019-04-30 13:59:59 -07001427 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1428 supportsProtectedContent());
1429 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Peiyong Linfb530cf2018-12-15 05:07:38 +00001430 StringAppendF(&result, "RenderEngine program cache size for unprotected context: %zu\n",
1431 cache.getSize(mEGLContext));
1432 StringAppendF(&result, "RenderEngine program cache size for protected context: %zu\n",
1433 cache.getSize(mProtectedEGLContext));
Yiwei Zhang5434a782018-12-05 18:06:32 -08001434 StringAppendF(&result, "RenderEngine last dataspace conversion: (%s) to (%s)\n",
1435 dataspaceDetails(static_cast<android_dataspace>(mDataSpace)).c_str(),
1436 dataspaceDetails(static_cast<android_dataspace>(mOutputDataSpace)).c_str());
Alec Mourief44c2d2019-07-15 15:27:22 -07001437 {
1438 std::lock_guard<std::mutex> lock(mRenderingMutex);
1439 StringAppendF(&result, "RenderEngine image cache size: %zu\n", mImageCache.size());
1440 StringAppendF(&result, "Dumping buffer ids...\n");
1441 for (const auto& [id, unused] : mImageCache) {
1442 StringAppendF(&result, "0x%" PRIx64 "\n", id);
1443 }
1444 }
1445 {
1446 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
1447 StringAppendF(&result, "RenderEngine framebuffer image cache size: %zu\n",
1448 mFramebufferImageCache.size());
1449 StringAppendF(&result, "Dumping buffer ids...\n");
1450 for (const auto& [id, unused] : mFramebufferImageCache) {
1451 StringAppendF(&result, "0x%" PRIx64 "\n", id);
1452 }
1453 }
Mathias Agopian3f844832013-08-07 21:24:32 -07001454}
1455
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001456GLESRenderEngine::GlesVersion GLESRenderEngine::parseGlesVersion(const char* str) {
Peiyong Linf11f39b2018-09-05 14:37:41 -07001457 int major, minor;
1458 if (sscanf(str, "OpenGL ES-CM %d.%d", &major, &minor) != 2) {
1459 if (sscanf(str, "OpenGL ES %d.%d", &major, &minor) != 2) {
1460 ALOGW("Unable to parse GL_VERSION string: \"%s\"", str);
1461 return GLES_VERSION_1_0;
1462 }
1463 }
1464
1465 if (major == 1 && minor == 0) return GLES_VERSION_1_0;
1466 if (major == 1 && minor >= 1) return GLES_VERSION_1_1;
1467 if (major == 2 && minor >= 0) return GLES_VERSION_2_0;
1468 if (major == 3 && minor >= 0) return GLES_VERSION_3_0;
1469
1470 ALOGW("Unrecognized OpenGL ES version: %d.%d", major, minor);
1471 return GLES_VERSION_1_0;
1472}
1473
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001474EGLContext GLESRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Peiyong Linfb530cf2018-12-15 05:07:38 +00001475 EGLContext shareContext, bool useContextPriority,
1476 Protection protection) {
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001477 EGLint renderableType = 0;
1478 if (config == EGL_NO_CONFIG) {
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001479 renderableType = EGL_OPENGL_ES3_BIT;
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001480 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1481 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1482 }
1483 EGLint contextClientVersion = 0;
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001484 if (renderableType & EGL_OPENGL_ES3_BIT) {
1485 contextClientVersion = 3;
1486 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001487 contextClientVersion = 2;
1488 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1489 contextClientVersion = 1;
1490 } else {
1491 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1492 }
1493
1494 std::vector<EGLint> contextAttributes;
Peiyong Linfb530cf2018-12-15 05:07:38 +00001495 contextAttributes.reserve(7);
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001496 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1497 contextAttributes.push_back(contextClientVersion);
1498 if (useContextPriority) {
1499 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
1500 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1501 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00001502 if (protection == Protection::PROTECTED) {
1503 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1504 contextAttributes.push_back(EGL_TRUE);
1505 }
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001506 contextAttributes.push_back(EGL_NONE);
1507
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001508 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1509
1510 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1511 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1512 // EGL_NO_CONTEXT so that we can abort.
1513 if (config != EGL_NO_CONFIG) {
1514 return context;
1515 }
1516 // If |config| is EGL_NO_CONFIG, we speculatively try to create GLES 3 context, so we should
1517 // try to fall back to GLES 2.
1518 contextAttributes[1] = 2;
1519 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1520 }
1521
1522 return context;
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001523}
1524
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001525EGLSurface GLESRenderEngine::createDummyEglPbufferSurface(EGLDisplay display, EGLConfig config,
Peiyong Linfb530cf2018-12-15 05:07:38 +00001526 int hwcFormat, Protection protection) {
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001527 EGLConfig dummyConfig = config;
1528 if (dummyConfig == EGL_NO_CONFIG) {
1529 dummyConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1530 }
1531 std::vector<EGLint> attributes;
Peiyong Linfb530cf2018-12-15 05:07:38 +00001532 attributes.reserve(7);
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001533 attributes.push_back(EGL_WIDTH);
1534 attributes.push_back(1);
1535 attributes.push_back(EGL_HEIGHT);
1536 attributes.push_back(1);
Peiyong Linfb530cf2018-12-15 05:07:38 +00001537 if (protection == Protection::PROTECTED) {
1538 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1539 attributes.push_back(EGL_TRUE);
1540 }
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001541 attributes.push_back(EGL_NONE);
1542
1543 return eglCreatePbufferSurface(display, dummyConfig, attributes.data());
1544}
1545
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001546bool GLESRenderEngine::isHdrDataSpace(const Dataspace dataSpace) const {
Peiyong Lina296b0c2018-04-30 16:55:29 -07001547 const Dataspace standard = static_cast<Dataspace>(dataSpace & Dataspace::STANDARD_MASK);
1548 const Dataspace transfer = static_cast<Dataspace>(dataSpace & Dataspace::TRANSFER_MASK);
1549 return standard == Dataspace::STANDARD_BT2020 &&
Peiyong Lin46080ef2018-10-26 18:43:14 -07001550 (transfer == Dataspace::TRANSFER_ST2084 || transfer == Dataspace::TRANSFER_HLG);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001551}
1552
1553// For convenience, we want to convert the input color space to XYZ color space first,
1554// and then convert from XYZ color space to output color space when
1555// - SDR and HDR contents are mixed, either SDR content will be converted to HDR or
1556// HDR content will be tone-mapped to SDR; Or,
1557// - there are HDR PQ and HLG contents presented at the same time, where we want to convert
1558// HLG content to PQ content.
1559// In either case above, we need to operate the Y value in XYZ color space. Thus, when either
1560// input data space or output data space is HDR data space, and the input transfer function
1561// doesn't match the output transfer function, we would enable an intermediate transfrom to
1562// XYZ color space.
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001563bool GLESRenderEngine::needsXYZTransformMatrix() const {
Peiyong Lina296b0c2018-04-30 16:55:29 -07001564 const bool isInputHdrDataSpace = isHdrDataSpace(mDataSpace);
1565 const bool isOutputHdrDataSpace = isHdrDataSpace(mOutputDataSpace);
1566 const Dataspace inputTransfer = static_cast<Dataspace>(mDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lin46080ef2018-10-26 18:43:14 -07001567 const Dataspace outputTransfer =
1568 static_cast<Dataspace>(mOutputDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001569
1570 return (isInputHdrDataSpace || isOutputHdrDataSpace) && inputTransfer != outputTransfer;
1571}
1572
Alec Mourid43ccab2019-03-13 12:23:45 -07001573bool GLESRenderEngine::isImageCachedForTesting(uint64_t bufferId) {
1574 std::lock_guard<std::mutex> lock(mRenderingMutex);
1575 const auto& cachedImage = mImageCache.find(bufferId);
1576 return cachedImage != mImageCache.end();
1577}
1578
1579bool GLESRenderEngine::isFramebufferImageCachedForTesting(uint64_t bufferId) {
Alec Mourief44c2d2019-07-15 15:27:22 -07001580 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
Alec Mourid43ccab2019-03-13 12:23:45 -07001581 return std::any_of(mFramebufferImageCache.cbegin(), mFramebufferImageCache.cend(),
1582 [=](std::pair<uint64_t, EGLImageKHR> image) {
1583 return image.first == bufferId;
1584 });
1585}
1586
Alec Mouri554d06e2018-12-20 00:15:33 -08001587// FlushTracer implementation
1588GLESRenderEngine::FlushTracer::FlushTracer(GLESRenderEngine* engine) : mEngine(engine) {
1589 mThread = std::thread(&GLESRenderEngine::FlushTracer::loop, this);
1590}
1591
1592GLESRenderEngine::FlushTracer::~FlushTracer() {
1593 {
1594 std::lock_guard<std::mutex> lock(mMutex);
1595 mRunning = false;
1596 }
1597 mCondition.notify_all();
1598 if (mThread.joinable()) {
1599 mThread.join();
1600 }
1601}
1602
1603void GLESRenderEngine::FlushTracer::queueSync(EGLSyncKHR sync) {
1604 std::lock_guard<std::mutex> lock(mMutex);
1605 char name[64];
1606 const uint64_t frameNum = mFramesQueued++;
1607 snprintf(name, sizeof(name), "Queueing sync for frame: %lu",
1608 static_cast<unsigned long>(frameNum));
1609 ATRACE_NAME(name);
1610 mQueue.push({sync, frameNum});
1611 ATRACE_INT("GPU Frames Outstanding", mQueue.size());
1612 mCondition.notify_one();
1613}
1614
1615void GLESRenderEngine::FlushTracer::loop() {
1616 while (mRunning) {
1617 QueueEntry entry;
1618 {
1619 std::lock_guard<std::mutex> lock(mMutex);
1620
1621 mCondition.wait(mMutex,
Alec Mouric15dd012019-01-15 15:30:38 -08001622 [&]() REQUIRES(mMutex) { return !mQueue.empty() || !mRunning; });
Alec Mouri554d06e2018-12-20 00:15:33 -08001623
1624 if (!mRunning) {
1625 // if mRunning is false, then FlushTracer is being destroyed, so
1626 // bail out now.
1627 break;
1628 }
1629 entry = mQueue.front();
1630 mQueue.pop();
1631 }
1632 {
1633 char name[64];
1634 snprintf(name, sizeof(name), "waiting for frame %lu",
1635 static_cast<unsigned long>(entry.mFrameNum));
1636 ATRACE_NAME(name);
1637 mEngine->waitSync(entry.mSync, 0);
1638 }
1639 }
1640}
1641
Vishnu Nair16efdbf2019-12-10 11:55:42 -08001642void GLESRenderEngine::handleShadow(const FloatRect& casterRect, float casterCornerRadius,
1643 const ShadowSettings& settings) {
1644 ATRACE_CALL();
1645 const float casterZ = settings.length / 2.0f;
1646 const GLShadowVertexGenerator shadows(casterRect, casterCornerRadius, casterZ,
1647 settings.casterIsTranslucent, settings.ambientColor,
1648 settings.spotColor, settings.lightPos,
1649 settings.lightRadius);
1650
1651 // setup mesh for both shadows
1652 Mesh mesh = Mesh::Builder()
1653 .setPrimitive(Mesh::TRIANGLES)
1654 .setVertices(shadows.getVertexCount(), 2 /* size */)
1655 .setShadowAttrs()
1656 .setIndices(shadows.getIndexCount())
1657 .build();
1658
1659 Mesh::VertexArray<vec2> position = mesh.getPositionArray<vec2>();
1660 Mesh::VertexArray<vec4> shadowColor = mesh.getShadowColorArray<vec4>();
1661 Mesh::VertexArray<vec3> shadowParams = mesh.getShadowParamsArray<vec3>();
1662 shadows.fillVertices(position, shadowColor, shadowParams);
1663 shadows.fillIndices(mesh.getIndicesArray());
1664
1665 mState.cornerRadius = 0.0f;
1666 mState.drawShadows = true;
Vishnu Nairf19544f2020-02-03 11:23:26 -08001667 setupLayerTexturing(mShadowTexture.getTexture());
Vishnu Nair16efdbf2019-12-10 11:55:42 -08001668 drawMesh(mesh);
1669 mState.drawShadows = false;
1670}
1671
Peiyong Lin46080ef2018-10-26 18:43:14 -07001672} // namespace gl
1673} // namespace renderengine
1674} // namespace android