blob: 98605baf824b4ce5e7a9c50bb67c6d8843f66bc0 [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"
54#include "filters/LensBlurFilter.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
288 // initialize the renderer while GL is current
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800289 std::unique_ptr<GLESRenderEngine> engine;
Peiyong Linf11f39b2018-09-05 14:37:41 -0700290 switch (version) {
291 case GLES_VERSION_1_0:
292 case GLES_VERSION_1_1:
293 LOG_ALWAYS_FATAL("SurfaceFlinger requires OpenGL ES 2.0 minimum to run.");
294 break;
295 case GLES_VERSION_2_0:
296 case GLES_VERSION_3_0:
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700297 engine = std::make_unique<GLESRenderEngine>(args, display, config, ctxt, dummy,
298 protectedContext, protectedDummy);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700299 break;
300 }
Peiyong Linf11f39b2018-09-05 14:37:41 -0700301
302 ALOGI("OpenGL ES informations:");
303 ALOGI("vendor : %s", extensions.getVendor());
304 ALOGI("renderer : %s", extensions.getRenderer());
305 ALOGI("version : %s", extensions.getVersion());
306 ALOGI("extensions: %s", extensions.getExtensions());
307 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
308 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
309
Peiyong Linf11f39b2018-09-05 14:37:41 -0700310 return engine;
311}
312
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800313EGLConfig GLESRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
Peiyong Linf11f39b2018-09-05 14:37:41 -0700314 status_t err;
315 EGLConfig config;
316
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800317 // First try to get an ES3 config
318 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700319 if (err != NO_ERROR) {
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800320 // If ES3 fails, try to get an ES2 config
321 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700322 if (err != NO_ERROR) {
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800323 // If ES2 still doesn't work, probably because we're on the emulator.
Peiyong Linf11f39b2018-09-05 14:37:41 -0700324 // try a simplified query
325 ALOGW("no suitable EGLConfig found, trying a simpler query");
326 err = selectEGLConfig(display, format, 0, &config);
327 if (err != NO_ERROR) {
328 // this EGL is too lame for android
329 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
330 }
331 }
332 }
333
334 if (logConfig) {
335 // print some debugging info
336 EGLint r, g, b, a;
337 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
338 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
339 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
340 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
341 ALOGI("EGL information:");
342 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
343 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
344 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
345 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
346 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
347 }
348
349 return config;
350}
351
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700352GLESRenderEngine::GLESRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
353 EGLConfig config, EGLContext ctxt, EGLSurface dummy,
354 EGLContext protectedContext, EGLSurface protectedDummy)
355 : renderengine::impl::RenderEngine(args),
Alec Mouri0a9c7b82018-11-16 13:05:25 -0800356 mEGLDisplay(display),
357 mEGLConfig(config),
358 mEGLContext(ctxt),
359 mDummySurface(dummy),
Peiyong Linfb530cf2018-12-15 05:07:38 +0000360 mProtectedEGLContext(protectedContext),
361 mProtectedDummySurface(protectedDummy),
Chia-I Wu93e14df2018-06-04 10:10:17 -0700362 mVpWidth(0),
363 mVpHeight(0),
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700364 mFramebufferImageCacheSize(args.imageCacheSize),
365 mUseColorManagement(args.useColorManagement) {
Mathias Agopian3f844832013-08-07 21:24:32 -0700366 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
367 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
368
369 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
370 glPixelStorei(GL_PACK_ALIGNMENT, 4);
371
Peiyong Linfb530cf2018-12-15 05:07:38 +0000372 // Initialize protected EGL Context.
373 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
374 EGLBoolean success = eglMakeCurrent(display, mProtectedDummySurface, mProtectedDummySurface,
375 mProtectedEGLContext);
376 ALOGE_IF(!success, "can't make protected context current");
377 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
378 glPixelStorei(GL_PACK_ALIGNMENT, 4);
379 success = eglMakeCurrent(display, mDummySurface, mDummySurface, mEGLContext);
380 LOG_ALWAYS_FATAL_IF(!success, "can't make default context current");
381 }
382
Chia-I Wub027f802017-11-29 14:00:52 -0800383 const uint16_t protTexData[] = {0};
Mathias Agopian3f844832013-08-07 21:24:32 -0700384 glGenTextures(1, &mProtectedTexName);
385 glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
386 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
387 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
388 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
389 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
Chia-I Wub027f802017-11-29 14:00:52 -0800390 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 -0700391
Chia-I Wub027f802017-11-29 14:00:52 -0800392 // mColorBlindnessCorrection = M;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600393
Peiyong Lin13effd12018-07-24 17:01:47 -0700394 if (mUseColorManagement) {
Valerie Haueb8e0762018-11-06 10:10:42 -0800395 const ColorSpace srgb(ColorSpace::sRGB());
396 const ColorSpace displayP3(ColorSpace::DisplayP3());
397 const ColorSpace bt2020(ColorSpace::BT2020());
Peiyong Lina296b0c2018-04-30 16:55:29 -0700398
399 // no chromatic adaptation needed since all color spaces use D65 for their white points.
Peiyong Lin70b26ce2018-09-18 19:02:39 -0700400 mSrgbToXyz = mat4(srgb.getRGBtoXYZ());
401 mDisplayP3ToXyz = mat4(displayP3.getRGBtoXYZ());
402 mBt2020ToXyz = mat4(bt2020.getRGBtoXYZ());
Peiyong Lin9b03c732018-05-17 10:14:02 -0700403 mXyzToSrgb = mat4(srgb.getXYZtoRGB());
Peiyong Lina296b0c2018-04-30 16:55:29 -0700404 mXyzToDisplayP3 = mat4(displayP3.getXYZtoRGB());
405 mXyzToBt2020 = mat4(bt2020.getXYZtoRGB());
Valerie Haueb8e0762018-11-06 10:10:42 -0800406
407 // Compute sRGB to Display P3 and BT2020 transform matrix.
408 // NOTE: For now, we are limiting output wide color space support to
409 // Display-P3 and BT2020 only.
410 mSrgbToDisplayP3 = mXyzToDisplayP3 * mSrgbToXyz;
411 mSrgbToBt2020 = mXyzToBt2020 * mSrgbToXyz;
412
413 // Compute Display P3 to sRGB and BT2020 transform matrix.
414 mDisplayP3ToSrgb = mXyzToSrgb * mDisplayP3ToXyz;
415 mDisplayP3ToBt2020 = mXyzToBt2020 * mDisplayP3ToXyz;
416
417 // Compute BT2020 to sRGB and Display P3 transform matrix
418 mBt2020ToSrgb = mXyzToSrgb * mBt2020ToXyz;
419 mBt2020ToDisplayP3 = mXyzToDisplayP3 * mBt2020ToXyz;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600420 }
Alec Mouri554d06e2018-12-20 00:15:33 -0800421
422 char value[PROPERTY_VALUE_MAX];
423 property_get("debug.egl.traceGpuCompletion", value, "0");
424 if (atoi(value)) {
425 mTraceGpuCompletion = true;
426 mFlushTracer = std::make_unique<FlushTracer>(this);
427 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800428
429 if (args.supportsBackgroundBlur) {
430 char isGaussian[PROPERTY_VALUE_MAX];
431 property_get("debug.sf.gaussianBlur", isGaussian, "1");
432 if (atoi(isGaussian)) {
433 mBlurFilter = new GaussianBlurFilter(*this);
434 } else {
435 mBlurFilter = new LensBlurFilter(*this);
436 }
437 checkErrors("BlurFilter creation");
438 }
439
Alec Mouri16a99402019-07-29 16:37:30 -0700440 mImageManager = std::make_unique<ImageManager>(this);
Alec Mouri820c7402019-01-23 13:02:39 -0800441 mDrawingBuffer = createFramebuffer();
Mathias Agopian3f844832013-08-07 21:24:32 -0700442}
443
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800444GLESRenderEngine::~GLESRenderEngine() {
Alec Mouri16a99402019-07-29 16:37:30 -0700445 // Destroy the image manager first.
446 mImageManager = nullptr;
Alec Mourid43ccab2019-03-13 12:23:45 -0700447 std::lock_guard<std::mutex> lock(mRenderingMutex);
448 unbindFrameBuffer(mDrawingBuffer.get());
449 mDrawingBuffer = nullptr;
450 while (!mFramebufferImageCache.empty()) {
451 EGLImageKHR expired = mFramebufferImageCache.front().second;
452 mFramebufferImageCache.pop_front();
453 eglDestroyImageKHR(mEGLDisplay, expired);
Ady Abrahama3b08ef2019-07-15 18:43:10 -0700454 DEBUG_EGL_IMAGE_TRACKER_DESTROY();
Alec Mourida4cf3b2019-02-12 15:33:01 -0800455 }
Alec Mourid43ccab2019-03-13 12:23:45 -0700456 mImageCache.clear();
Peiyong Linf11f39b2018-09-05 14:37:41 -0700457 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
458 eglTerminate(mEGLDisplay);
459}
Mathias Agopian3f844832013-08-07 21:24:32 -0700460
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800461std::unique_ptr<Framebuffer> GLESRenderEngine::createFramebuffer() {
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700462 return std::make_unique<GLFramebuffer>(*this);
463}
464
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800465std::unique_ptr<Image> GLESRenderEngine::createImage() {
Peiyong Linf1bada92018-08-29 09:39:31 -0700466 return std::make_unique<GLImage>(*this);
467}
468
Alec Mouri820c7402019-01-23 13:02:39 -0800469Framebuffer* GLESRenderEngine::getFramebufferForDrawing() {
470 return mDrawingBuffer.get();
471}
472
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800473void GLESRenderEngine::primeCache() const {
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700474 ProgramCache::getInstance().primeCache(mInProtectedContext ? mProtectedEGLContext : mEGLContext,
475 mArgs.useColorManagement,
476 mArgs.precacheToneMapperShaderOnly);
Peiyong Linf1bada92018-08-29 09:39:31 -0700477}
478
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800479base::unique_fd GLESRenderEngine::flush() {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000480 ATRACE_CALL();
Peiyong Lin60bedb52018-09-05 10:47:31 -0700481 if (!GLExtensions::getInstance().hasNativeFenceSync()) {
482 return base::unique_fd();
483 }
484
485 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
486 if (sync == EGL_NO_SYNC_KHR) {
487 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
488 return base::unique_fd();
489 }
490
491 // native fence fd will not be populated until flush() is done.
492 glFlush();
493
494 // get the fence fd
495 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
496 eglDestroySyncKHR(mEGLDisplay, sync);
497 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
498 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
499 }
500
Alec Mouri554d06e2018-12-20 00:15:33 -0800501 // Only trace if we have a valid fence, as current usage falls back to
502 // calling finish() if the fence fd is invalid.
503 if (CC_UNLIKELY(mTraceGpuCompletion && mFlushTracer) && fenceFd.get() >= 0) {
504 mFlushTracer->queueSync(eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, nullptr));
505 }
506
Peiyong Lin60bedb52018-09-05 10:47:31 -0700507 return fenceFd;
508}
509
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800510bool GLESRenderEngine::finish() {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000511 ATRACE_CALL();
Peiyong Lin60bedb52018-09-05 10:47:31 -0700512 if (!GLExtensions::getInstance().hasFenceSync()) {
513 ALOGW("no synchronization support");
514 return false;
515 }
516
517 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, nullptr);
518 if (sync == EGL_NO_SYNC_KHR) {
519 ALOGW("failed to create EGL fence sync: %#x", eglGetError());
520 return false;
521 }
522
Alec Mouri554d06e2018-12-20 00:15:33 -0800523 if (CC_UNLIKELY(mTraceGpuCompletion && mFlushTracer)) {
524 mFlushTracer->queueSync(eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, nullptr));
525 }
526
527 return waitSync(sync, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR);
528}
529
530bool GLESRenderEngine::waitSync(EGLSyncKHR sync, EGLint flags) {
531 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync, flags, 2000000000 /*2 sec*/);
Peiyong Lin60bedb52018-09-05 10:47:31 -0700532 EGLint error = eglGetError();
533 eglDestroySyncKHR(mEGLDisplay, sync);
534 if (result != EGL_CONDITION_SATISFIED_KHR) {
535 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
536 ALOGW("fence wait timed out");
537 } else {
538 ALOGW("error waiting on EGL fence: %#x", error);
539 }
540 return false;
541 }
542
543 return true;
544}
545
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800546bool GLESRenderEngine::waitFence(base::unique_fd fenceFd) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700547 if (!GLExtensions::getInstance().hasNativeFenceSync() ||
548 !GLExtensions::getInstance().hasWaitSync()) {
549 return false;
550 }
551
Peiyong Lin35a114c2019-04-25 14:37:13 -0700552 // release the fd and transfer the ownership to EGLSync
553 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
Peiyong Lin60bedb52018-09-05 10:47:31 -0700554 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
555 if (sync == EGL_NO_SYNC_KHR) {
556 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
557 return false;
558 }
559
Peiyong Lin60bedb52018-09-05 10:47:31 -0700560 // XXX: The spec draft is inconsistent as to whether this should return an
561 // EGLint or void. Ignore the return value for now, as it's not strictly
562 // needed.
563 eglWaitSyncKHR(mEGLDisplay, sync, 0);
564 EGLint error = eglGetError();
565 eglDestroySyncKHR(mEGLDisplay, sync);
566 if (error != EGL_SUCCESS) {
567 ALOGE("failed to wait for EGL native fence sync: %#x", error);
568 return false;
569 }
570
571 return true;
572}
573
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800574void GLESRenderEngine::clearWithColor(float red, float green, float blue, float alpha) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000575 ATRACE_CALL();
576 glDisable(GL_BLEND);
Peiyong Linf11f39b2018-09-05 14:37:41 -0700577 glClearColor(red, green, blue, alpha);
578 glClear(GL_COLOR_BUFFER_BIT);
579}
580
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800581void GLESRenderEngine::fillRegionWithColor(const Region& region, float red, float green, float blue,
582 float alpha) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700583 size_t c;
584 Rect const* r = region.getArray(&c);
Vishnu Nair440992f2019-12-09 19:53:19 -0800585 Mesh mesh = Mesh::Builder()
586 .setPrimitive(Mesh::TRIANGLES)
587 .setVertices(c * 6 /* count */, 2 /* size */)
588 .build();
Peiyong Lin60bedb52018-09-05 10:47:31 -0700589 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
590 for (size_t i = 0; i < c; i++, r++) {
591 position[i * 6 + 0].x = r->left;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700592 position[i * 6 + 0].y = r->top;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700593 position[i * 6 + 1].x = r->left;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700594 position[i * 6 + 1].y = r->bottom;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700595 position[i * 6 + 2].x = r->right;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700596 position[i * 6 + 2].y = r->bottom;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700597 position[i * 6 + 3].x = r->left;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700598 position[i * 6 + 3].y = r->top;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700599 position[i * 6 + 4].x = r->right;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700600 position[i * 6 + 4].y = r->bottom;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700601 position[i * 6 + 5].x = r->right;
Chia-I Wu28e3a252018-09-07 12:05:02 -0700602 position[i * 6 + 5].y = r->top;
Peiyong Lin60bedb52018-09-05 10:47:31 -0700603 }
604 setupFillWithColor(red, green, blue, alpha);
605 drawMesh(mesh);
606}
607
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800608void GLESRenderEngine::setScissor(const Rect& region) {
Peiyong Lin1c097612019-03-22 16:21:46 -0700609 glScissor(region.left, region.top, region.getWidth(), region.getHeight());
Peiyong Lin60bedb52018-09-05 10:47:31 -0700610 glEnable(GL_SCISSOR_TEST);
611}
612
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800613void GLESRenderEngine::disableScissor() {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700614 glDisable(GL_SCISSOR_TEST);
615}
616
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800617void GLESRenderEngine::genTextures(size_t count, uint32_t* names) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700618 glGenTextures(count, names);
619}
620
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800621void GLESRenderEngine::deleteTextures(size_t count, uint32_t const* names) {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700622 glDeleteTextures(count, names);
623}
624
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800625void GLESRenderEngine::bindExternalTextureImage(uint32_t texName, const Image& image) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000626 ATRACE_CALL();
Peiyong Linf1bada92018-08-29 09:39:31 -0700627 const GLImage& glImage = static_cast<const GLImage&>(image);
628 const GLenum target = GL_TEXTURE_EXTERNAL_OES;
629
630 glBindTexture(target, texName);
631 if (glImage.getEGLImage() != EGL_NO_IMAGE_KHR) {
Peiyong Lin46080ef2018-10-26 18:43:14 -0700632 glEGLImageTargetTexture2DOES(target, static_cast<GLeglImageOES>(glImage.getEGLImage()));
Peiyong Linf1bada92018-08-29 09:39:31 -0700633 }
Mathias Agopian3f844832013-08-07 21:24:32 -0700634}
635
Alec Mourid7b3a8b2019-03-21 11:44:18 -0700636status_t GLESRenderEngine::bindExternalTextureBuffer(uint32_t texName,
637 const sp<GraphicBuffer>& buffer,
638 const sp<Fence>& bufferFence) {
Alec Mouri16a99402019-07-29 16:37:30 -0700639 if (buffer == nullptr) {
640 return BAD_VALUE;
Alec Mourid7b3a8b2019-03-21 11:44:18 -0700641 }
642
Alec Mouri16a99402019-07-29 16:37:30 -0700643 ATRACE_CALL();
644
645 bool found = false;
646 {
647 std::lock_guard<std::mutex> lock(mRenderingMutex);
648 auto cachedImage = mImageCache.find(buffer->getId());
649 found = (cachedImage != mImageCache.end());
650 }
651
652 // If we couldn't find the image in the cache at this time, then either
653 // SurfaceFlinger messed up registering the buffer ahead of time or we got
654 // backed up creating other EGLImages.
655 if (!found) {
656 status_t cacheResult = mImageManager->cache(buffer);
657 if (cacheResult != NO_ERROR) {
658 return cacheResult;
659 }
660 }
661
662 // Whether or not we needed to cache, re-check mImageCache to make sure that
663 // there's an EGLImage. The current threading model guarantees that we don't
664 // destroy a cached image until it's really not needed anymore (i.e. this
665 // function should not be called), so the only possibility is that something
666 // terrible went wrong and we should just bind something and move on.
Alec Mouri3d7c5612019-07-09 13:51:37 -0700667 {
668 std::lock_guard<std::mutex> lock(mRenderingMutex);
669 auto cachedImage = mImageCache.find(buffer->getId());
Alec Mourid7b3a8b2019-03-21 11:44:18 -0700670
Alec Mouri3d7c5612019-07-09 13:51:37 -0700671 if (cachedImage == mImageCache.end()) {
672 // We failed creating the image if we got here, so bail out.
Alec Mouri16a99402019-07-29 16:37:30 -0700673 ALOGE("Failed to create an EGLImage when rendering");
Alec Mouri3d7c5612019-07-09 13:51:37 -0700674 bindExternalTextureImage(texName, *createImage());
675 return NO_INIT;
676 }
677
678 bindExternalTextureImage(texName, *cachedImage->second);
Alec Mouri0d5e1eb2018-11-10 20:40:12 -0800679 }
680
Alec Mouri0d5e1eb2018-11-10 20:40:12 -0800681 // Wait for the new buffer to be ready.
682 if (bufferFence != nullptr && bufferFence->isValid()) {
683 if (GLExtensions::getInstance().hasWaitSync()) {
684 base::unique_fd fenceFd(bufferFence->dup());
685 if (fenceFd == -1) {
686 ALOGE("error dup'ing fence fd: %d", errno);
687 return -errno;
688 }
689 if (!waitFence(std::move(fenceFd))) {
690 ALOGE("failed to wait on fence fd");
691 return UNKNOWN_ERROR;
692 }
693 } else {
694 status_t err = bufferFence->waitForever("RenderEngine::bindExternalTextureBuffer");
695 if (err != NO_ERROR) {
696 ALOGE("error waiting for fence: %d", err);
697 return err;
698 }
699 }
700 }
Alec Mouri539319f2018-12-19 17:56:23 -0800701
Alec Mouri0d5e1eb2018-11-10 20:40:12 -0800702 return NO_ERROR;
703}
704
Alec Mouri16a99402019-07-29 16:37:30 -0700705void GLESRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
706 mImageManager->cacheAsync(buffer, nullptr);
707}
708
709std::shared_ptr<ImageManager::Barrier> GLESRenderEngine::cacheExternalTextureBufferForTesting(
710 const sp<GraphicBuffer>& buffer) {
711 auto barrier = std::make_shared<ImageManager::Barrier>();
712 mImageManager->cacheAsync(buffer, barrier);
713 return barrier;
714}
715
716status_t GLESRenderEngine::cacheExternalTextureBufferInternal(const sp<GraphicBuffer>& buffer) {
Alec Mouri3d7c5612019-07-09 13:51:37 -0700717 if (buffer == nullptr) {
718 return BAD_VALUE;
719 }
720
721 {
722 std::lock_guard<std::mutex> lock(mRenderingMutex);
723 if (mImageCache.count(buffer->getId()) > 0) {
724 // If there's already an image then fail fast here.
725 return NO_ERROR;
726 }
727 }
728 ATRACE_CALL();
729
730 // Create the image without holding a lock so that we don't block anything.
731 std::unique_ptr<Image> newImage = createImage();
732
733 bool created = newImage->setNativeWindowBuffer(buffer->getNativeBuffer(),
734 buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
735 if (!created) {
736 ALOGE("Failed to create image. size=%ux%u st=%u usage=%#" PRIx64 " fmt=%d",
737 buffer->getWidth(), buffer->getHeight(), buffer->getStride(), buffer->getUsage(),
738 buffer->getPixelFormat());
739 return NO_INIT;
740 }
741
742 {
743 std::lock_guard<std::mutex> lock(mRenderingMutex);
744 if (mImageCache.count(buffer->getId()) > 0) {
745 // In theory it's possible for another thread to recache the image,
746 // so bail out if another thread won.
747 return NO_ERROR;
748 }
749 mImageCache.insert(std::make_pair(buffer->getId(), std::move(newImage)));
750 }
751
752 return NO_ERROR;
753}
754
Alec Mourib5c4f352019-02-19 19:46:38 -0800755void GLESRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Alec Mouri16a99402019-07-29 16:37:30 -0700756 mImageManager->releaseAsync(bufferId, nullptr);
757}
758
759std::shared_ptr<ImageManager::Barrier> GLESRenderEngine::unbindExternalTextureBufferForTesting(
760 uint64_t bufferId) {
761 auto barrier = std::make_shared<ImageManager::Barrier>();
762 mImageManager->releaseAsync(bufferId, barrier);
763 return barrier;
764}
765
766void GLESRenderEngine::unbindExternalTextureBufferInternal(uint64_t bufferId) {
767 std::unique_ptr<Image> image;
768 {
769 std::lock_guard<std::mutex> lock(mRenderingMutex);
770 const auto& cachedImage = mImageCache.find(bufferId);
771
772 if (cachedImage != mImageCache.end()) {
773 ALOGV("Destroying image for buffer: %" PRIu64, bufferId);
774 // Move the buffer out of cache first, so that we can destroy
775 // without holding the cache's lock.
776 image = std::move(cachedImage->second);
777 mImageCache.erase(bufferId);
778 return;
779 }
Alec Mouri539319f2018-12-19 17:56:23 -0800780 }
Alec Mourib5c4f352019-02-19 19:46:38 -0800781 ALOGV("Failed to find image for buffer: %" PRIu64, bufferId);
Alec Mouri539319f2018-12-19 17:56:23 -0800782}
783
Alec Mouri7c94edb2018-12-03 21:23:26 -0800784FloatRect GLESRenderEngine::setupLayerCropping(const LayerSettings& layer, Mesh& mesh) {
785 // Translate win by the rounded corners rect coordinates, to have all values in
786 // layer coordinate space.
787 FloatRect cropWin = layer.geometry.boundaries;
788 const FloatRect& roundedCornersCrop = layer.geometry.roundedCornersCrop;
789 cropWin.left -= roundedCornersCrop.left;
790 cropWin.right -= roundedCornersCrop.left;
791 cropWin.top -= roundedCornersCrop.top;
792 cropWin.bottom -= roundedCornersCrop.top;
793 Mesh::VertexArray<vec2> cropCoords(mesh.getCropCoordArray<vec2>());
794 cropCoords[0] = vec2(cropWin.left, cropWin.top);
795 cropCoords[1] = vec2(cropWin.left, cropWin.top + cropWin.getHeight());
796 cropCoords[2] = vec2(cropWin.right, cropWin.top + cropWin.getHeight());
797 cropCoords[3] = vec2(cropWin.right, cropWin.top);
798
799 setupCornerRadiusCropSize(roundedCornersCrop.getWidth(), roundedCornersCrop.getHeight());
800 return cropWin;
801}
802
Peiyong Lin1c097612019-03-22 16:21:46 -0700803void GLESRenderEngine::handleRoundedCorners(const DisplaySettings& display,
804 const LayerSettings& layer, const Mesh& mesh) {
805 // We separate the layer into 3 parts essentially, such that we only turn on blending for the
806 // top rectangle and the bottom rectangle, and turn off blending for the middle rectangle.
807 FloatRect bounds = layer.geometry.roundedCornersCrop;
Peiyong Linb1925962019-04-01 16:37:10 -0700808
809 // Firstly, we need to convert the coordination from layer native coordination space to
810 // device coordination space.
Peiyong Lin1c097612019-03-22 16:21:46 -0700811 const auto transformMatrix = display.globalTransform * layer.geometry.positionTransform;
812 const vec4 leftTopCoordinate(bounds.left, bounds.top, 1.0, 1.0);
813 const vec4 rightBottomCoordinate(bounds.right, bounds.bottom, 1.0, 1.0);
814 const vec4 leftTopCoordinateInBuffer = transformMatrix * leftTopCoordinate;
815 const vec4 rightBottomCoordinateInBuffer = transformMatrix * rightBottomCoordinate;
816 bounds = FloatRect(leftTopCoordinateInBuffer[0], leftTopCoordinateInBuffer[1],
817 rightBottomCoordinateInBuffer[0], rightBottomCoordinateInBuffer[1]);
Peiyong Lin1c097612019-03-22 16:21:46 -0700818
Peiyong Linb1925962019-04-01 16:37:10 -0700819 // Secondly, if the display is rotated, we need to undo the rotation on coordination and
820 // align the (left, top) and (right, bottom) coordination with the device coordination
821 // space.
822 switch (display.orientation) {
823 case ui::Transform::ROT_90:
824 std::swap(bounds.left, bounds.right);
825 break;
826 case ui::Transform::ROT_180:
827 std::swap(bounds.left, bounds.right);
828 std::swap(bounds.top, bounds.bottom);
829 break;
830 case ui::Transform::ROT_270:
831 std::swap(bounds.top, bounds.bottom);
832 break;
833 default:
834 break;
835 }
836
837 // Finally, we cut the layer into 3 parts, with top and bottom parts having rounded corners
838 // and the middle part without rounded corners.
839 const int32_t radius = ceil(layer.geometry.roundedCornersRadius);
Peiyong Lin1c097612019-03-22 16:21:46 -0700840 const Rect topRect(bounds.left, bounds.top, bounds.right, bounds.top + radius);
841 setScissor(topRect);
842 drawMesh(mesh);
843 const Rect bottomRect(bounds.left, bounds.bottom - radius, bounds.right, bounds.bottom);
844 setScissor(bottomRect);
845 drawMesh(mesh);
846
847 // The middle part of the layer can turn off blending.
Lucas Dupinc9691d52019-09-26 13:46:04 -0700848 if (topRect.bottom < bottomRect.top) {
849 const Rect middleRect(bounds.left, bounds.top + radius, bounds.right,
850 bounds.bottom - radius);
851 setScissor(middleRect);
852 mState.cornerRadius = 0.0;
853 disableBlending();
854 drawMesh(mesh);
855 }
Peiyong Lin1c097612019-03-22 16:21:46 -0700856 disableScissor();
857}
858
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800859status_t GLESRenderEngine::bindFrameBuffer(Framebuffer* framebuffer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000860 ATRACE_CALL();
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700861 GLFramebuffer* glFramebuffer = static_cast<GLFramebuffer*>(framebuffer);
862 EGLImageKHR eglImage = glFramebuffer->getEGLImage();
863 uint32_t textureName = glFramebuffer->getTextureName();
864 uint32_t framebufferName = glFramebuffer->getFramebufferName();
865
866 // Bind the texture and turn our EGLImage into a texture
867 glBindTexture(GL_TEXTURE_2D, textureName);
868 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)eglImage);
869
870 // Bind the Framebuffer to render into
871 glBindFramebuffer(GL_FRAMEBUFFER, framebufferName);
Peiyong Lin46080ef2018-10-26 18:43:14 -0700872 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureName, 0);
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700873
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700874 uint32_t glStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
Peiyong Lin46080ef2018-10-26 18:43:14 -0700875 ALOGE_IF(glStatus != GL_FRAMEBUFFER_COMPLETE_OES, "glCheckFramebufferStatusOES error %d",
876 glStatus);
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700877
878 return glStatus == GL_FRAMEBUFFER_COMPLETE_OES ? NO_ERROR : BAD_VALUE;
879}
880
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800881void GLESRenderEngine::unbindFrameBuffer(Framebuffer* /* framebuffer */) {
Alec Mouri820c7402019-01-23 13:02:39 -0800882 ATRACE_CALL();
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700883
884 // back to main framebuffer
885 glBindFramebuffer(GL_FRAMEBUFFER, 0);
Peiyong Line5a9a7f2018-08-30 15:32:13 -0700886}
887
Peiyong Lin7e219eb2018-12-03 05:40:42 -0800888void GLESRenderEngine::checkErrors() const {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800889 checkErrors(nullptr);
890}
891
892void GLESRenderEngine::checkErrors(const char* tag) const {
Peiyong Lin60bedb52018-09-05 10:47:31 -0700893 do {
894 // there could be more than one error flag
895 GLenum error = glGetError();
896 if (error == GL_NO_ERROR) break;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800897 if (tag == nullptr) {
898 ALOGE("GL error 0x%04x", int(error));
899 } else {
900 ALOGE("GL error: %s -> 0x%04x", tag, int(error));
901 }
Peiyong Lin60bedb52018-09-05 10:47:31 -0700902 } while (true);
903}
904
Peiyong Linfb530cf2018-12-15 05:07:38 +0000905bool GLESRenderEngine::supportsProtectedContent() const {
906 return mProtectedEGLContext != EGL_NO_CONTEXT;
907}
908
909bool GLESRenderEngine::useProtectedContext(bool useProtectedContext) {
910 if (useProtectedContext == mInProtectedContext) {
911 return true;
912 }
913 if (useProtectedContext && mProtectedEGLContext == EGL_NO_CONTEXT) {
914 return false;
915 }
916 const EGLSurface surface = useProtectedContext ? mProtectedDummySurface : mDummySurface;
917 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
918 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
919 if (success) {
920 mInProtectedContext = useProtectedContext;
921 }
922 return success;
923}
Alec Mourida4cf3b2019-02-12 15:33:01 -0800924EGLImageKHR GLESRenderEngine::createFramebufferImageIfNeeded(ANativeWindowBuffer* nativeBuffer,
Alec Mourife0d72b2019-03-21 14:05:56 -0700925 bool isProtected,
926 bool useFramebufferCache) {
Alec Mourida4cf3b2019-02-12 15:33:01 -0800927 sp<GraphicBuffer> graphicBuffer = GraphicBuffer::from(nativeBuffer);
Alec Mourife0d72b2019-03-21 14:05:56 -0700928 if (useFramebufferCache) {
Alec Mourief44c2d2019-07-15 15:27:22 -0700929 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
Alec Mourife0d72b2019-03-21 14:05:56 -0700930 for (const auto& image : mFramebufferImageCache) {
931 if (image.first == graphicBuffer->getId()) {
932 return image.second;
933 }
Alec Mourida4cf3b2019-02-12 15:33:01 -0800934 }
935 }
936 EGLint attributes[] = {
937 isProtected ? EGL_PROTECTED_CONTENT_EXT : EGL_NONE,
938 isProtected ? EGL_TRUE : EGL_NONE,
939 EGL_NONE,
940 };
941 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
942 nativeBuffer, attributes);
Alec Mourife0d72b2019-03-21 14:05:56 -0700943 if (useFramebufferCache) {
944 if (image != EGL_NO_IMAGE_KHR) {
Alec Mourief44c2d2019-07-15 15:27:22 -0700945 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
Alec Mourife0d72b2019-03-21 14:05:56 -0700946 if (mFramebufferImageCache.size() >= mFramebufferImageCacheSize) {
947 EGLImageKHR expired = mFramebufferImageCache.front().second;
948 mFramebufferImageCache.pop_front();
949 eglDestroyImageKHR(mEGLDisplay, expired);
Ady Abrahama3b08ef2019-07-15 18:43:10 -0700950 DEBUG_EGL_IMAGE_TRACKER_DESTROY();
Alec Mourife0d72b2019-03-21 14:05:56 -0700951 }
952 mFramebufferImageCache.push_back({graphicBuffer->getId(), image});
Alec Mourida4cf3b2019-02-12 15:33:01 -0800953 }
Alec Mourida4cf3b2019-02-12 15:33:01 -0800954 }
Ady Abrahama3b08ef2019-07-15 18:43:10 -0700955
956 if (image != EGL_NO_IMAGE_KHR) {
957 DEBUG_EGL_IMAGE_TRACKER_CREATE();
958 }
Alec Mourida4cf3b2019-02-12 15:33:01 -0800959 return image;
960}
Peiyong Linfb530cf2018-12-15 05:07:38 +0000961
Alec Mouri1089aed2018-10-25 21:33:57 -0700962status_t GLESRenderEngine::drawLayers(const DisplaySettings& display,
Vishnu Nair9b079a22020-01-21 14:36:08 -0800963 const std::vector<const LayerSettings*>& layers,
Alec Mouri1089aed2018-10-25 21:33:57 -0700964 ANativeWindowBuffer* const buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -0700965 const bool useFramebufferCache, base::unique_fd&& bufferFence,
966 base::unique_fd* drawFence) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000967 ATRACE_CALL();
Alec Mouri1089aed2018-10-25 21:33:57 -0700968 if (layers.empty()) {
969 ALOGV("Drawing empty layer stack");
970 return NO_ERROR;
971 }
972
Alec Mouri6338c9d2019-02-07 16:57:51 -0800973 if (bufferFence.get() >= 0 && !waitFence(std::move(bufferFence))) {
974 ATRACE_NAME("Waiting before draw");
975 sync_wait(bufferFence.get(), -1);
976 }
977
Alec Mourid43ccab2019-03-13 12:23:45 -0700978 if (buffer == nullptr) {
979 ALOGE("No output buffer provided. Aborting GPU composition.");
980 return BAD_VALUE;
981 }
982
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800983 std::unique_ptr<BindNativeBufferAsFramebuffer> fbo;
984 // Let's find the topmost layer requesting background blur (if any.)
985 // Blurs in multiple layers are not supported, given the cost of the shader.
986 const LayerSettings* blurLayer = nullptr;
987 if (CC_LIKELY(mBlurFilter != nullptr)) {
Vishnu Nair9b079a22020-01-21 14:36:08 -0800988 for (auto const layer : layers) {
989 if (layer->backgroundBlurRadius > 0) {
990 blurLayer = layer;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800991 }
992 }
993 }
Alec Mouri1089aed2018-10-25 21:33:57 -0700994
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800995 if (blurLayer == nullptr) {
996 fbo = std::make_unique<BindNativeBufferAsFramebuffer>(*this, buffer, useFramebufferCache);
997 if (fbo->getStatus() != NO_ERROR) {
998 ALOGE("Failed to bind framebuffer! Aborting GPU composition for buffer (%p).",
999 buffer->handle);
1000 checkErrors();
1001 return fbo->getStatus();
1002 }
1003 setViewportAndProjection(display.physicalDisplay, display.clip);
1004 } else {
1005 setViewportAndProjection(display.physicalDisplay, display.clip);
Lucas Dupinf82ed8f2020-01-17 12:11:07 -08001006 auto status = mBlurFilter->setAsDrawTarget(display, blurLayer->backgroundBlurRadius);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001007 if (status != NO_ERROR) {
1008 ALOGE("Failed to prepare blur filter! Aborting GPU composition for buffer (%p).",
1009 buffer->handle);
1010 checkErrors();
1011 return status;
1012 }
Alec Mourif0497272019-03-11 15:53:11 -07001013 }
Alec Mouri3d7c5612019-07-09 13:51:37 -07001014
1015 // clear the entire buffer, sometimes when we reuse buffers we'd persist
1016 // ghost images otherwise.
1017 // we also require a full transparent framebuffer for overlays. This is
1018 // probably not quite efficient on all GPUs, since we could filter out
1019 // opaque layers.
1020 clearWithColor(0.0, 0.0, 0.0, 0.0);
1021
Alec Mouri3d7c5612019-07-09 13:51:37 -07001022 setOutputDataSpace(display.outputDataspace);
1023 setDisplayMaxLuminance(display.maxLuminance);
1024
1025 mat4 projectionMatrix = mState.projectionMatrix * display.globalTransform;
1026 mState.projectionMatrix = projectionMatrix;
1027 if (!display.clearRegion.isEmpty()) {
1028 glDisable(GL_BLEND);
1029 fillRegionWithColor(display.clearRegion, 0.0, 0.0, 0.0, 1.0);
1030 }
1031
Vishnu Nair440992f2019-12-09 19:53:19 -08001032 Mesh mesh = Mesh::Builder()
1033 .setPrimitive(Mesh::TRIANGLE_FAN)
1034 .setVertices(4 /* count */, 2 /* size */)
1035 .setTexCoords(2 /* size */)
1036 .setCropCoords(2 /* size */)
1037 .build();
Vishnu Nair9b079a22020-01-21 14:36:08 -08001038 for (auto const layer : layers) {
1039 if (blurLayer == layer) {
Lucas Dupinf82ed8f2020-01-17 12:11:07 -08001040 auto status = mBlurFilter->prepare();
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001041 if (status != NO_ERROR) {
1042 ALOGE("Failed to render blur effect! Aborting GPU composition for buffer (%p).",
1043 buffer->handle);
1044 checkErrors("Can't render first blur pass");
1045 return status;
1046 }
1047
1048 fbo = std::make_unique<BindNativeBufferAsFramebuffer>(*this, buffer,
1049 useFramebufferCache);
1050 status = fbo->getStatus();
1051 if (status != NO_ERROR) {
1052 ALOGE("Failed to bind framebuffer! Aborting GPU composition for buffer (%p).",
1053 buffer->handle);
1054 checkErrors("Can't bind native framebuffer");
1055 return status;
1056 }
1057 setViewportAndProjection(display.physicalDisplay, display.clip);
1058
1059 status = mBlurFilter->render();
1060 if (status != NO_ERROR) {
1061 ALOGE("Failed to render blur effect! Aborting GPU composition for buffer (%p).",
1062 buffer->handle);
1063 checkErrors("Can't render blur filter");
1064 return status;
1065 }
1066 }
1067
Vishnu Nair9b079a22020-01-21 14:36:08 -08001068 mState.maxMasteringLuminance = layer->source.buffer.maxMasteringLuminance;
1069 mState.maxContentLuminance = layer->source.buffer.maxContentLuminance;
1070 mState.projectionMatrix = projectionMatrix * layer->geometry.positionTransform;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001071
Vishnu Nair9b079a22020-01-21 14:36:08 -08001072 const FloatRect bounds = layer->geometry.boundaries;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001073 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1074 position[0] = vec2(bounds.left, bounds.top);
1075 position[1] = vec2(bounds.left, bounds.bottom);
1076 position[2] = vec2(bounds.right, bounds.bottom);
1077 position[3] = vec2(bounds.right, bounds.top);
1078
Vishnu Nair9b079a22020-01-21 14:36:08 -08001079 setupLayerCropping(*layer, mesh);
1080 setColorTransform(display.colorTransform * layer->colorTransform);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001081
1082 bool usePremultipliedAlpha = true;
1083 bool disableTexture = true;
1084 bool isOpaque = false;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001085 if (layer->source.buffer.buffer != nullptr) {
Alec Mouri3d7c5612019-07-09 13:51:37 -07001086 disableTexture = false;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001087 isOpaque = layer->source.buffer.isOpaque;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001088
Vishnu Nair9b079a22020-01-21 14:36:08 -08001089 sp<GraphicBuffer> gBuf = layer->source.buffer.buffer;
1090 bindExternalTextureBuffer(layer->source.buffer.textureName, gBuf,
1091 layer->source.buffer.fence);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001092
Vishnu Nair9b079a22020-01-21 14:36:08 -08001093 usePremultipliedAlpha = layer->source.buffer.usePremultipliedAlpha;
1094 Texture texture(Texture::TEXTURE_EXTERNAL, layer->source.buffer.textureName);
1095 mat4 texMatrix = layer->source.buffer.textureTransform;
Alec Mouri3d7c5612019-07-09 13:51:37 -07001096
1097 texture.setMatrix(texMatrix.asArray());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001098 texture.setFiltering(layer->source.buffer.useTextureFiltering);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001099
1100 texture.setDimensions(gBuf->getWidth(), gBuf->getHeight());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001101 setSourceY410BT2020(layer->source.buffer.isY410BT2020);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001102
1103 renderengine::Mesh::VertexArray<vec2> texCoords(mesh.getTexCoordArray<vec2>());
1104 texCoords[0] = vec2(0.0, 0.0);
1105 texCoords[1] = vec2(0.0, 1.0);
1106 texCoords[2] = vec2(1.0, 1.0);
1107 texCoords[3] = vec2(1.0, 0.0);
1108 setupLayerTexturing(texture);
1109 }
1110
Vishnu Nair9b079a22020-01-21 14:36:08 -08001111 const half3 solidColor = layer->source.solidColor;
1112 const half4 color = half4(solidColor.r, solidColor.g, solidColor.b, layer->alpha);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001113 // Buffer sources will have a black solid color ignored in the shader,
1114 // so in that scenario the solid color passed here is arbitrary.
1115 setupLayerBlending(usePremultipliedAlpha, isOpaque, disableTexture, color,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001116 layer->geometry.roundedCornersRadius);
1117 if (layer->disableBlending) {
Alec Mouri3d7c5612019-07-09 13:51:37 -07001118 glDisable(GL_BLEND);
1119 }
Vishnu Nair9b079a22020-01-21 14:36:08 -08001120 setSourceDataSpace(layer->sourceDataspace);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001121
Vishnu Nair9b079a22020-01-21 14:36:08 -08001122 if (layer->shadow.length > 0.0f) {
1123 handleShadow(layer->geometry.boundaries, layer->geometry.roundedCornersRadius,
1124 layer->shadow);
Vishnu Nair440992f2019-12-09 19:53:19 -08001125 }
Alec Mouri3d7c5612019-07-09 13:51:37 -07001126 // We only want to do a special handling for rounded corners when having rounded corners
1127 // is the only reason it needs to turn on blending, otherwise, we handle it like the
1128 // usual way since it needs to turn on blending anyway.
Vishnu Nair9b079a22020-01-21 14:36:08 -08001129 else if (layer->geometry.roundedCornersRadius > 0.0 && color.a >= 1.0f && isOpaque) {
1130 handleRoundedCorners(display, *layer, mesh);
Alec Mouri3d7c5612019-07-09 13:51:37 -07001131 } else {
1132 drawMesh(mesh);
1133 }
1134
1135 // Cleanup if there's a buffer source
Vishnu Nair9b079a22020-01-21 14:36:08 -08001136 if (layer->source.buffer.buffer != nullptr) {
Alec Mouri3d7c5612019-07-09 13:51:37 -07001137 disableBlending();
1138 setSourceY410BT2020(false);
1139 disableTexturing();
1140 }
1141 }
1142
1143 if (drawFence != nullptr) {
1144 *drawFence = flush();
1145 }
1146 // If flush failed or we don't support native fences, we need to force the
1147 // gl command stream to be executed.
1148 if (drawFence == nullptr || drawFence->get() < 0) {
1149 bool success = finish();
1150 if (!success) {
1151 ALOGE("Failed to flush RenderEngine commands");
1152 checkErrors();
1153 // Chances are, something illegal happened (either the caller passed
1154 // us bad parameters, or we messed up our shader generation).
1155 return INVALID_OPERATION;
1156 }
1157 }
1158
1159 checkErrors();
Alec Mouri6e57f682018-09-29 20:45:08 -07001160 return NO_ERROR;
1161}
1162
Alec Mouri1089aed2018-10-25 21:33:57 -07001163void GLESRenderEngine::setViewportAndProjection(Rect viewport, Rect clip) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001164 ATRACE_CALL();
Alec Mouri1089aed2018-10-25 21:33:57 -07001165 mVpWidth = viewport.getWidth();
1166 mVpHeight = viewport.getHeight();
1167
1168 // We pass the the top left corner instead of the bottom left corner,
1169 // because since we're rendering off-screen first.
1170 glViewport(viewport.left, viewport.top, mVpWidth, mVpHeight);
1171
1172 mState.projectionMatrix = mat4::ortho(clip.left, clip.right, clip.top, clip.bottom, 0, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001173}
1174
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001175void GLESRenderEngine::setupLayerBlending(bool premultipliedAlpha, bool opaque, bool disableTexture,
1176 const half4& color, float cornerRadius) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001177 mState.isPremultipliedAlpha = premultipliedAlpha;
1178 mState.isOpaque = opaque;
1179 mState.color = color;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001180 mState.cornerRadius = cornerRadius;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001181
chaviw13fdc492017-06-27 12:40:18 -07001182 if (disableTexture) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001183 mState.textureEnabled = false;
chaviw13fdc492017-06-27 12:40:18 -07001184 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001185
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001186 if (color.a < 1.0f || !opaque || cornerRadius > 0.0f) {
Mathias Agopian3f844832013-08-07 21:24:32 -07001187 glEnable(GL_BLEND);
1188 glBlendFunc(premultipliedAlpha ? GL_ONE : GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1189 } else {
1190 glDisable(GL_BLEND);
1191 }
1192}
1193
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001194void GLESRenderEngine::setSourceY410BT2020(bool enable) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001195 mState.isY410BT2020 = enable;
Chia-I Wu131d3762018-01-11 14:35:27 -08001196}
1197
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001198void GLESRenderEngine::setSourceDataSpace(Dataspace source) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08001199 mDataSpace = source;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001200}
1201
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001202void GLESRenderEngine::setOutputDataSpace(Dataspace dataspace) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08001203 mOutputDataSpace = dataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001204}
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001205
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001206void GLESRenderEngine::setDisplayMaxLuminance(const float maxLuminance) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001207 mState.displayMaxLuminance = maxLuminance;
Peiyong Linfb069302018-04-25 14:34:31 -07001208}
1209
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001210void GLESRenderEngine::setupLayerTexturing(const Texture& texture) {
Mathias Agopian49457ac2013-08-14 18:20:17 -07001211 GLuint target = texture.getTextureTarget();
1212 glBindTexture(target, texture.getTextureName());
Mathias Agopian3f844832013-08-07 21:24:32 -07001213 GLenum filter = GL_NEAREST;
Mathias Agopian49457ac2013-08-14 18:20:17 -07001214 if (texture.getFiltering()) {
Mathias Agopian3f844832013-08-07 21:24:32 -07001215 filter = GL_LINEAR;
1216 }
Mathias Agopian49457ac2013-08-14 18:20:17 -07001217 glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1218 glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1219 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
1220 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);
Mathias Agopian3f844832013-08-07 21:24:32 -07001221
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001222 mState.texture = texture;
1223 mState.textureEnabled = true;
Mathias Agopian3f844832013-08-07 21:24:32 -07001224}
1225
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001226void GLESRenderEngine::setColorTransform(const mat4& colorTransform) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001227 mState.colorMatrix = colorTransform;
Dan Stozaf0087992014-10-20 15:46:09 -07001228}
1229
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001230void GLESRenderEngine::disableTexturing() {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001231 mState.textureEnabled = false;
Mathias Agopian3f844832013-08-07 21:24:32 -07001232}
1233
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001234void GLESRenderEngine::disableBlending() {
Mathias Agopian3f844832013-08-07 21:24:32 -07001235 glDisable(GL_BLEND);
1236}
1237
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001238void GLESRenderEngine::setupFillWithColor(float r, float g, float b, float a) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001239 mState.isPremultipliedAlpha = true;
1240 mState.isOpaque = false;
1241 mState.color = half4(r, g, b, a);
1242 mState.textureEnabled = false;
Mathias Agopian3f844832013-08-07 21:24:32 -07001243 glDisable(GL_BLEND);
Mathias Agopian3f844832013-08-07 21:24:32 -07001244}
1245
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001246void GLESRenderEngine::setupCornerRadiusCropSize(float width, float height) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001247 mState.cropSize = half2(width, height);
1248}
1249
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001250void GLESRenderEngine::drawMesh(const Mesh& mesh) {
Dan Stoza2713c302018-03-28 17:07:36 -07001251 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07001252 if (mesh.getTexCoordsSize()) {
1253 glEnableVertexAttribArray(Program::texCoords);
Chia-I Wub027f802017-11-29 14:00:52 -08001254 glVertexAttribPointer(Program::texCoords, mesh.getTexCoordsSize(), GL_FLOAT, GL_FALSE,
1255 mesh.getByteStride(), mesh.getTexCoords());
Mathias Agopian3f844832013-08-07 21:24:32 -07001256 }
1257
Chia-I Wub027f802017-11-29 14:00:52 -08001258 glVertexAttribPointer(Program::position, mesh.getVertexSize(), GL_FLOAT, GL_FALSE,
1259 mesh.getByteStride(), mesh.getPositions());
Mathias Agopian3f844832013-08-07 21:24:32 -07001260
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001261 if (mState.cornerRadius > 0.0f) {
1262 glEnableVertexAttribArray(Program::cropCoords);
1263 glVertexAttribPointer(Program::cropCoords, mesh.getVertexSize(), GL_FLOAT, GL_FALSE,
1264 mesh.getByteStride(), mesh.getCropCoords());
1265 }
1266
Vishnu Nair440992f2019-12-09 19:53:19 -08001267 if (mState.drawShadows) {
1268 glEnableVertexAttribArray(Program::shadowColor);
1269 glVertexAttribPointer(Program::shadowColor, mesh.getShadowColorSize(), GL_FLOAT, GL_FALSE,
1270 mesh.getByteStride(), mesh.getShadowColor());
1271
1272 glEnableVertexAttribArray(Program::shadowParams);
1273 glVertexAttribPointer(Program::shadowParams, mesh.getShadowParamsSize(), GL_FLOAT, GL_FALSE,
1274 mesh.getByteStride(), mesh.getShadowParams());
1275 }
1276
1277 Description managedState = mState;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001278 // By default, DISPLAY_P3 is the only supported wide color output. However,
1279 // when HDR content is present, hardware composer may be able to handle
1280 // BT2020 data space, in that case, the output data space is set to be
1281 // BT2020_HLG or BT2020_PQ respectively. In GPU fall back we need
1282 // to respect this and convert non-HDR content to HDR format.
Peiyong Lin13effd12018-07-24 17:01:47 -07001283 if (mUseColorManagement) {
Peiyong Lina296b0c2018-04-30 16:55:29 -07001284 Dataspace inputStandard = static_cast<Dataspace>(mDataSpace & Dataspace::STANDARD_MASK);
1285 Dataspace inputTransfer = static_cast<Dataspace>(mDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lin46080ef2018-10-26 18:43:14 -07001286 Dataspace outputStandard =
1287 static_cast<Dataspace>(mOutputDataSpace & Dataspace::STANDARD_MASK);
1288 Dataspace outputTransfer =
1289 static_cast<Dataspace>(mOutputDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001290 bool needsXYZConversion = needsXYZTransformMatrix();
1291
Valerie Haueb8e0762018-11-06 10:10:42 -08001292 // NOTE: if the input standard of the input dataspace is not STANDARD_DCI_P3 or
1293 // STANDARD_BT2020, it will be treated as STANDARD_BT709
1294 if (inputStandard != Dataspace::STANDARD_DCI_P3 &&
1295 inputStandard != Dataspace::STANDARD_BT2020) {
1296 inputStandard = Dataspace::STANDARD_BT709;
1297 }
1298
Peiyong Lina296b0c2018-04-30 16:55:29 -07001299 if (needsXYZConversion) {
1300 // The supported input color spaces are standard RGB, Display P3 and BT2020.
1301 switch (inputStandard) {
1302 case Dataspace::STANDARD_DCI_P3:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001303 managedState.inputTransformMatrix = mDisplayP3ToXyz;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001304 break;
1305 case Dataspace::STANDARD_BT2020:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001306 managedState.inputTransformMatrix = mBt2020ToXyz;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001307 break;
1308 default:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001309 managedState.inputTransformMatrix = mSrgbToXyz;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001310 break;
1311 }
1312
Peiyong Lin9b03c732018-05-17 10:14:02 -07001313 // The supported output color spaces are BT2020, Display P3 and standard RGB.
Peiyong Lina296b0c2018-04-30 16:55:29 -07001314 switch (outputStandard) {
1315 case Dataspace::STANDARD_BT2020:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001316 managedState.outputTransformMatrix = mXyzToBt2020;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001317 break;
Peiyong Lin9b03c732018-05-17 10:14:02 -07001318 case Dataspace::STANDARD_DCI_P3:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001319 managedState.outputTransformMatrix = mXyzToDisplayP3;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001320 break;
Peiyong Lin9b03c732018-05-17 10:14:02 -07001321 default:
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001322 managedState.outputTransformMatrix = mXyzToSrgb;
Peiyong Lin9b03c732018-05-17 10:14:02 -07001323 break;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001324 }
1325 } else if (inputStandard != outputStandard) {
1326 // At this point, the input data space and output data space could be both
1327 // HDR data spaces, but they match each other, we do nothing in this case.
1328 // In addition to the case above, the input data space could be
1329 // - scRGB linear
1330 // - scRGB non-linear
1331 // - sRGB
1332 // - Display P3
Valerie Haueb8e0762018-11-06 10:10:42 -08001333 // - BT2020
Peiyong Lina296b0c2018-04-30 16:55:29 -07001334 // The output data spaces could be
1335 // - sRGB
1336 // - Display P3
Valerie Haueb8e0762018-11-06 10:10:42 -08001337 // - BT2020
1338 switch (outputStandard) {
1339 case Dataspace::STANDARD_BT2020:
1340 if (inputStandard == Dataspace::STANDARD_BT709) {
1341 managedState.outputTransformMatrix = mSrgbToBt2020;
1342 } else if (inputStandard == Dataspace::STANDARD_DCI_P3) {
1343 managedState.outputTransformMatrix = mDisplayP3ToBt2020;
1344 }
1345 break;
1346 case Dataspace::STANDARD_DCI_P3:
1347 if (inputStandard == Dataspace::STANDARD_BT709) {
1348 managedState.outputTransformMatrix = mSrgbToDisplayP3;
1349 } else if (inputStandard == Dataspace::STANDARD_BT2020) {
1350 managedState.outputTransformMatrix = mBt2020ToDisplayP3;
1351 }
1352 break;
1353 default:
1354 if (inputStandard == Dataspace::STANDARD_DCI_P3) {
1355 managedState.outputTransformMatrix = mDisplayP3ToSrgb;
1356 } else if (inputStandard == Dataspace::STANDARD_BT2020) {
1357 managedState.outputTransformMatrix = mBt2020ToSrgb;
1358 }
1359 break;
Peiyong Lina296b0c2018-04-30 16:55:29 -07001360 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001361 }
Peiyong Lina296b0c2018-04-30 16:55:29 -07001362
1363 // we need to convert the RGB value to linear space and convert it back when:
1364 // - there is a color matrix that is not an identity matrix, or
1365 // - there is an output transform matrix that is not an identity matrix, or
1366 // - the input transfer function doesn't match the output transfer function.
Peiyong Lin13effd12018-07-24 17:01:47 -07001367 if (managedState.hasColorMatrix() || managedState.hasOutputTransformMatrix() ||
Chia-I Wud49d6692018-06-27 07:17:41 +08001368 inputTransfer != outputTransfer) {
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001369 managedState.inputTransferFunction =
Peiyong Lin46080ef2018-10-26 18:43:14 -07001370 Description::dataSpaceToTransferFunction(inputTransfer);
Peiyong Lin70b26ce2018-09-18 19:02:39 -07001371 managedState.outputTransferFunction =
Peiyong Lin46080ef2018-10-26 18:43:14 -07001372 Description::dataSpaceToTransferFunction(outputTransfer);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001373 }
Vishnu Nair440992f2019-12-09 19:53:19 -08001374 }
Peiyong Lina296b0c2018-04-30 16:55:29 -07001375
Vishnu Nair440992f2019-12-09 19:53:19 -08001376 ProgramCache::getInstance().useProgram(mInProtectedContext ? mProtectedEGLContext : mEGLContext,
1377 managedState);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001378
Vishnu Nair440992f2019-12-09 19:53:19 -08001379 if (mState.drawShadows) {
1380 glDrawElements(mesh.getPrimitive(), mesh.getIndexCount(), GL_UNSIGNED_SHORT,
1381 mesh.getIndices());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001382 } else {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001383 glDrawArrays(mesh.getPrimitive(), 0, mesh.getVertexCount());
1384 }
Mathias Agopian3f844832013-08-07 21:24:32 -07001385
Vishnu Nair440992f2019-12-09 19:53:19 -08001386 if (mUseColorManagement && outputDebugPPMs) {
1387 static uint64_t managedColorFrameCount = 0;
1388 std::ostringstream out;
1389 out << "/data/texture_out" << managedColorFrameCount++;
1390 writePPM(out.str().c_str(), mVpWidth, mVpHeight);
1391 }
1392
Mathias Agopian3f844832013-08-07 21:24:32 -07001393 if (mesh.getTexCoordsSize()) {
1394 glDisableVertexAttribArray(Program::texCoords);
1395 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001396
1397 if (mState.cornerRadius > 0.0f) {
1398 glDisableVertexAttribArray(Program::cropCoords);
1399 }
Vishnu Nair440992f2019-12-09 19:53:19 -08001400
1401 if (mState.drawShadows) {
1402 glDisableVertexAttribArray(Program::shadowColor);
1403 glDisableVertexAttribArray(Program::shadowParams);
1404 }
Mathias Agopian3f844832013-08-07 21:24:32 -07001405}
1406
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001407size_t GLESRenderEngine::getMaxTextureSize() const {
Peiyong Linf1bada92018-08-29 09:39:31 -07001408 return mMaxTextureSize;
1409}
1410
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001411size_t GLESRenderEngine::getMaxViewportDims() const {
Peiyong Linf1bada92018-08-29 09:39:31 -07001412 return mMaxViewportDims[0] < mMaxViewportDims[1] ? mMaxViewportDims[0] : mMaxViewportDims[1];
1413}
1414
Yiwei Zhang5434a782018-12-05 18:06:32 -08001415void GLESRenderEngine::dump(std::string& result) {
Peiyong Linf11f39b2018-09-05 14:37:41 -07001416 const GLExtensions& extensions = GLExtensions::getInstance();
Peiyong Linfb530cf2018-12-15 05:07:38 +00001417 ProgramCache& cache = ProgramCache::getInstance();
Peiyong Linf11f39b2018-09-05 14:37:41 -07001418
Yiwei Zhang5434a782018-12-05 18:06:32 -08001419 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1420 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
Yiwei Zhang5434a782018-12-05 18:06:32 -08001421 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1422 extensions.getVersion());
1423 StringAppendF(&result, "%s\n", extensions.getExtensions());
Peiyong Line62c5cb2019-04-30 13:59:59 -07001424 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1425 supportsProtectedContent());
1426 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Peiyong Linfb530cf2018-12-15 05:07:38 +00001427 StringAppendF(&result, "RenderEngine program cache size for unprotected context: %zu\n",
1428 cache.getSize(mEGLContext));
1429 StringAppendF(&result, "RenderEngine program cache size for protected context: %zu\n",
1430 cache.getSize(mProtectedEGLContext));
Yiwei Zhang5434a782018-12-05 18:06:32 -08001431 StringAppendF(&result, "RenderEngine last dataspace conversion: (%s) to (%s)\n",
1432 dataspaceDetails(static_cast<android_dataspace>(mDataSpace)).c_str(),
1433 dataspaceDetails(static_cast<android_dataspace>(mOutputDataSpace)).c_str());
Alec Mourief44c2d2019-07-15 15:27:22 -07001434 {
1435 std::lock_guard<std::mutex> lock(mRenderingMutex);
1436 StringAppendF(&result, "RenderEngine image cache size: %zu\n", mImageCache.size());
1437 StringAppendF(&result, "Dumping buffer ids...\n");
1438 for (const auto& [id, unused] : mImageCache) {
1439 StringAppendF(&result, "0x%" PRIx64 "\n", id);
1440 }
1441 }
1442 {
1443 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
1444 StringAppendF(&result, "RenderEngine framebuffer image cache size: %zu\n",
1445 mFramebufferImageCache.size());
1446 StringAppendF(&result, "Dumping buffer ids...\n");
1447 for (const auto& [id, unused] : mFramebufferImageCache) {
1448 StringAppendF(&result, "0x%" PRIx64 "\n", id);
1449 }
1450 }
Mathias Agopian3f844832013-08-07 21:24:32 -07001451}
1452
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001453GLESRenderEngine::GlesVersion GLESRenderEngine::parseGlesVersion(const char* str) {
Peiyong Linf11f39b2018-09-05 14:37:41 -07001454 int major, minor;
1455 if (sscanf(str, "OpenGL ES-CM %d.%d", &major, &minor) != 2) {
1456 if (sscanf(str, "OpenGL ES %d.%d", &major, &minor) != 2) {
1457 ALOGW("Unable to parse GL_VERSION string: \"%s\"", str);
1458 return GLES_VERSION_1_0;
1459 }
1460 }
1461
1462 if (major == 1 && minor == 0) return GLES_VERSION_1_0;
1463 if (major == 1 && minor >= 1) return GLES_VERSION_1_1;
1464 if (major == 2 && minor >= 0) return GLES_VERSION_2_0;
1465 if (major == 3 && minor >= 0) return GLES_VERSION_3_0;
1466
1467 ALOGW("Unrecognized OpenGL ES version: %d.%d", major, minor);
1468 return GLES_VERSION_1_0;
1469}
1470
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001471EGLContext GLESRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Peiyong Linfb530cf2018-12-15 05:07:38 +00001472 EGLContext shareContext, bool useContextPriority,
1473 Protection protection) {
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001474 EGLint renderableType = 0;
1475 if (config == EGL_NO_CONFIG) {
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001476 renderableType = EGL_OPENGL_ES3_BIT;
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001477 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1478 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1479 }
1480 EGLint contextClientVersion = 0;
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001481 if (renderableType & EGL_OPENGL_ES3_BIT) {
1482 contextClientVersion = 3;
1483 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001484 contextClientVersion = 2;
1485 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1486 contextClientVersion = 1;
1487 } else {
1488 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1489 }
1490
1491 std::vector<EGLint> contextAttributes;
Peiyong Linfb530cf2018-12-15 05:07:38 +00001492 contextAttributes.reserve(7);
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001493 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1494 contextAttributes.push_back(contextClientVersion);
1495 if (useContextPriority) {
1496 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
1497 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1498 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00001499 if (protection == Protection::PROTECTED) {
1500 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1501 contextAttributes.push_back(EGL_TRUE);
1502 }
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001503 contextAttributes.push_back(EGL_NONE);
1504
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001505 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1506
1507 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1508 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1509 // EGL_NO_CONTEXT so that we can abort.
1510 if (config != EGL_NO_CONFIG) {
1511 return context;
1512 }
1513 // If |config| is EGL_NO_CONFIG, we speculatively try to create GLES 3 context, so we should
1514 // try to fall back to GLES 2.
1515 contextAttributes[1] = 2;
1516 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1517 }
1518
1519 return context;
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001520}
1521
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001522EGLSurface GLESRenderEngine::createDummyEglPbufferSurface(EGLDisplay display, EGLConfig config,
Peiyong Linfb530cf2018-12-15 05:07:38 +00001523 int hwcFormat, Protection protection) {
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001524 EGLConfig dummyConfig = config;
1525 if (dummyConfig == EGL_NO_CONFIG) {
1526 dummyConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1527 }
1528 std::vector<EGLint> attributes;
Peiyong Linfb530cf2018-12-15 05:07:38 +00001529 attributes.reserve(7);
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001530 attributes.push_back(EGL_WIDTH);
1531 attributes.push_back(1);
1532 attributes.push_back(EGL_HEIGHT);
1533 attributes.push_back(1);
Peiyong Linfb530cf2018-12-15 05:07:38 +00001534 if (protection == Protection::PROTECTED) {
1535 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1536 attributes.push_back(EGL_TRUE);
1537 }
Peiyong Lina5e9f1b2018-11-27 22:49:37 -08001538 attributes.push_back(EGL_NONE);
1539
1540 return eglCreatePbufferSurface(display, dummyConfig, attributes.data());
1541}
1542
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001543bool GLESRenderEngine::isHdrDataSpace(const Dataspace dataSpace) const {
Peiyong Lina296b0c2018-04-30 16:55:29 -07001544 const Dataspace standard = static_cast<Dataspace>(dataSpace & Dataspace::STANDARD_MASK);
1545 const Dataspace transfer = static_cast<Dataspace>(dataSpace & Dataspace::TRANSFER_MASK);
1546 return standard == Dataspace::STANDARD_BT2020 &&
Peiyong Lin46080ef2018-10-26 18:43:14 -07001547 (transfer == Dataspace::TRANSFER_ST2084 || transfer == Dataspace::TRANSFER_HLG);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001548}
1549
1550// For convenience, we want to convert the input color space to XYZ color space first,
1551// and then convert from XYZ color space to output color space when
1552// - SDR and HDR contents are mixed, either SDR content will be converted to HDR or
1553// HDR content will be tone-mapped to SDR; Or,
1554// - there are HDR PQ and HLG contents presented at the same time, where we want to convert
1555// HLG content to PQ content.
1556// In either case above, we need to operate the Y value in XYZ color space. Thus, when either
1557// input data space or output data space is HDR data space, and the input transfer function
1558// doesn't match the output transfer function, we would enable an intermediate transfrom to
1559// XYZ color space.
Peiyong Lin7e219eb2018-12-03 05:40:42 -08001560bool GLESRenderEngine::needsXYZTransformMatrix() const {
Peiyong Lina296b0c2018-04-30 16:55:29 -07001561 const bool isInputHdrDataSpace = isHdrDataSpace(mDataSpace);
1562 const bool isOutputHdrDataSpace = isHdrDataSpace(mOutputDataSpace);
1563 const Dataspace inputTransfer = static_cast<Dataspace>(mDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lin46080ef2018-10-26 18:43:14 -07001564 const Dataspace outputTransfer =
1565 static_cast<Dataspace>(mOutputDataSpace & Dataspace::TRANSFER_MASK);
Peiyong Lina296b0c2018-04-30 16:55:29 -07001566
1567 return (isInputHdrDataSpace || isOutputHdrDataSpace) && inputTransfer != outputTransfer;
1568}
1569
Alec Mourid43ccab2019-03-13 12:23:45 -07001570bool GLESRenderEngine::isImageCachedForTesting(uint64_t bufferId) {
1571 std::lock_guard<std::mutex> lock(mRenderingMutex);
1572 const auto& cachedImage = mImageCache.find(bufferId);
1573 return cachedImage != mImageCache.end();
1574}
1575
1576bool GLESRenderEngine::isFramebufferImageCachedForTesting(uint64_t bufferId) {
Alec Mourief44c2d2019-07-15 15:27:22 -07001577 std::lock_guard<std::mutex> lock(mFramebufferImageCacheMutex);
Alec Mourid43ccab2019-03-13 12:23:45 -07001578 return std::any_of(mFramebufferImageCache.cbegin(), mFramebufferImageCache.cend(),
1579 [=](std::pair<uint64_t, EGLImageKHR> image) {
1580 return image.first == bufferId;
1581 });
1582}
1583
Alec Mouri554d06e2018-12-20 00:15:33 -08001584// FlushTracer implementation
1585GLESRenderEngine::FlushTracer::FlushTracer(GLESRenderEngine* engine) : mEngine(engine) {
1586 mThread = std::thread(&GLESRenderEngine::FlushTracer::loop, this);
1587}
1588
1589GLESRenderEngine::FlushTracer::~FlushTracer() {
1590 {
1591 std::lock_guard<std::mutex> lock(mMutex);
1592 mRunning = false;
1593 }
1594 mCondition.notify_all();
1595 if (mThread.joinable()) {
1596 mThread.join();
1597 }
1598}
1599
1600void GLESRenderEngine::FlushTracer::queueSync(EGLSyncKHR sync) {
1601 std::lock_guard<std::mutex> lock(mMutex);
1602 char name[64];
1603 const uint64_t frameNum = mFramesQueued++;
1604 snprintf(name, sizeof(name), "Queueing sync for frame: %lu",
1605 static_cast<unsigned long>(frameNum));
1606 ATRACE_NAME(name);
1607 mQueue.push({sync, frameNum});
1608 ATRACE_INT("GPU Frames Outstanding", mQueue.size());
1609 mCondition.notify_one();
1610}
1611
1612void GLESRenderEngine::FlushTracer::loop() {
1613 while (mRunning) {
1614 QueueEntry entry;
1615 {
1616 std::lock_guard<std::mutex> lock(mMutex);
1617
1618 mCondition.wait(mMutex,
Alec Mouric15dd012019-01-15 15:30:38 -08001619 [&]() REQUIRES(mMutex) { return !mQueue.empty() || !mRunning; });
Alec Mouri554d06e2018-12-20 00:15:33 -08001620
1621 if (!mRunning) {
1622 // if mRunning is false, then FlushTracer is being destroyed, so
1623 // bail out now.
1624 break;
1625 }
1626 entry = mQueue.front();
1627 mQueue.pop();
1628 }
1629 {
1630 char name[64];
1631 snprintf(name, sizeof(name), "waiting for frame %lu",
1632 static_cast<unsigned long>(entry.mFrameNum));
1633 ATRACE_NAME(name);
1634 mEngine->waitSync(entry.mSync, 0);
1635 }
1636 }
1637}
1638
Vishnu Nair16efdbf2019-12-10 11:55:42 -08001639void GLESRenderEngine::handleShadow(const FloatRect& casterRect, float casterCornerRadius,
1640 const ShadowSettings& settings) {
1641 ATRACE_CALL();
1642 const float casterZ = settings.length / 2.0f;
1643 const GLShadowVertexGenerator shadows(casterRect, casterCornerRadius, casterZ,
1644 settings.casterIsTranslucent, settings.ambientColor,
1645 settings.spotColor, settings.lightPos,
1646 settings.lightRadius);
1647
1648 // setup mesh for both shadows
1649 Mesh mesh = Mesh::Builder()
1650 .setPrimitive(Mesh::TRIANGLES)
1651 .setVertices(shadows.getVertexCount(), 2 /* size */)
1652 .setShadowAttrs()
1653 .setIndices(shadows.getIndexCount())
1654 .build();
1655
1656 Mesh::VertexArray<vec2> position = mesh.getPositionArray<vec2>();
1657 Mesh::VertexArray<vec4> shadowColor = mesh.getShadowColorArray<vec4>();
1658 Mesh::VertexArray<vec3> shadowParams = mesh.getShadowParamsArray<vec3>();
1659 shadows.fillVertices(position, shadowColor, shadowParams);
1660 shadows.fillIndices(mesh.getIndicesArray());
1661
1662 mState.cornerRadius = 0.0f;
1663 mState.drawShadows = true;
1664 drawMesh(mesh);
1665 mState.drawShadows = false;
1666}
1667
Peiyong Lin46080ef2018-10-26 18:43:14 -07001668} // namespace gl
1669} // namespace renderengine
1670} // namespace android