1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18 #define LOG_TAG "GLWorker"
19 
20 #include <string>
21 #include <sstream>
22 
23 #include <sys/resource.h>
24 
25 #include <sync/sync.h>
26 #include <sw_sync.h>
27 
28 #include <hardware/hardware.h>
29 #include <hardware/hwcomposer.h>
30 
31 #include <ui/GraphicBuffer.h>
32 #include <ui/PixelFormat.h>
33 
34 #include <utils/Trace.h>
35 
36 #include "glworker.h"
37 
38 #include "seperate_rects.h"
39 
40 // TODO(zachr): use hwc_drm_bo to turn buffer handles into textures
41 #ifndef EGL_NATIVE_HANDLE_ANDROID_NVX
42 #define EGL_NATIVE_HANDLE_ANDROID_NVX 0x322A
43 #endif
44 
45 #define MAX_OVERLAPPING_LAYERS 64
46 
47 namespace android {
48 
49 typedef seperate_rects::Rect<float> FRect;
50 typedef seperate_rects::RectSet<uint64_t, float> FRectSet;
51 
GetGLError(void)52 static const char *GetGLError(void) {
53   switch (glGetError()) {
54     case GL_NO_ERROR:
55       return "GL_NO_ERROR";
56     case GL_INVALID_ENUM:
57       return "GL_INVALID_ENUM";
58     case GL_INVALID_VALUE:
59       return "GL_INVALID_VALUE";
60     case GL_INVALID_OPERATION:
61       return "GL_INVALID_OPERATION";
62     case GL_INVALID_FRAMEBUFFER_OPERATION:
63       return "GL_INVALID_FRAMEBUFFER_OPERATION";
64     case GL_OUT_OF_MEMORY:
65       return "GL_OUT_OF_MEMORY";
66     default:
67       return "Unknown error";
68   }
69 }
70 
GetGLFramebufferError(void)71 static const char *GetGLFramebufferError(void) {
72   switch (glCheckFramebufferStatus(GL_FRAMEBUFFER)) {
73     case GL_FRAMEBUFFER_COMPLETE:
74       return "GL_FRAMEBUFFER_COMPLETE";
75     case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
76       return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
77     case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
78       return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
79     case GL_FRAMEBUFFER_UNSUPPORTED:
80       return "GL_FRAMEBUFFER_UNSUPPORTED";
81     case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
82       return "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
83     default:
84       return "Unknown error";
85   }
86 }
87 
GetEGLError(void)88 static const char *GetEGLError(void) {
89   switch (eglGetError()) {
90     case EGL_SUCCESS:
91       return "EGL_SUCCESS";
92     case EGL_NOT_INITIALIZED:
93       return "EGL_NOT_INITIALIZED";
94     case EGL_BAD_ACCESS:
95       return "EGL_BAD_ACCESS";
96     case EGL_BAD_ALLOC:
97       return "EGL_BAD_ALLOC";
98     case EGL_BAD_ATTRIBUTE:
99       return "EGL_BAD_ATTRIBUTE";
100     case EGL_BAD_CONTEXT:
101       return "EGL_BAD_CONTEXT";
102     case EGL_BAD_CONFIG:
103       return "EGL_BAD_CONFIG";
104     case EGL_BAD_CURRENT_SURFACE:
105       return "EGL_BAD_CURRENT_SURFACE";
106     case EGL_BAD_DISPLAY:
107       return "EGL_BAD_DISPLAY";
108     case EGL_BAD_SURFACE:
109       return "EGL_BAD_SURFACE";
110     case EGL_BAD_MATCH:
111       return "EGL_BAD_MATCH";
112     case EGL_BAD_PARAMETER:
113       return "EGL_BAD_PARAMETER";
114     case EGL_BAD_NATIVE_PIXMAP:
115       return "EGL_BAD_NATIVE_PIXMAP";
116     case EGL_BAD_NATIVE_WINDOW:
117       return "EGL_BAD_NATIVE_WINDOW";
118     case EGL_CONTEXT_LOST:
119       return "EGL_CONTEXT_LOST";
120     default:
121       return "Unknown error";
122   }
123 }
124 
HasExtension(const char * extension,const char * extensions)125 static bool HasExtension(const char *extension, const char *extensions) {
126   const char *start, *where, *terminator;
127   start = extensions;
128   for (;;) {
129     where = (char *)strstr((const char *)start, extension);
130     if (!where)
131       break;
132     terminator = where + strlen(extension);
133     if (where == start || *(where - 1) == ' ')
134       if (*terminator == ' ' || *terminator == '\0')
135         return true;
136     start = terminator;
137   }
138   return false;
139 }
140 
CompileAndCheckShader(GLenum type,unsigned source_count,const GLchar ** sources,std::string * shader_log)141 static AutoGLShader CompileAndCheckShader(GLenum type, unsigned source_count,
142                                           const GLchar **sources,
143                                           std::string *shader_log) {
144   GLint status;
145   AutoGLShader shader(glCreateShader(type));
146   if (shader.get() == 0) {
147     *shader_log = "glCreateShader failed";
148     return 0;
149   }
150   glShaderSource(shader.get(), source_count, sources, NULL);
151   glCompileShader(shader.get());
152   glGetShaderiv(shader.get(), GL_COMPILE_STATUS, &status);
153   if (!status) {
154     if (shader_log) {
155       GLint log_length;
156       glGetShaderiv(shader.get(), GL_INFO_LOG_LENGTH, &log_length);
157       shader_log->resize(log_length);
158       glGetShaderInfoLog(shader.get(), log_length, NULL, &(*shader_log)[0]);
159     }
160     return 0;
161   }
162 
163   return shader;
164 }
165 
GenerateShaders(std::vector<AutoGLProgram> * blend_programs)166 static int GenerateShaders(std::vector<AutoGLProgram> *blend_programs) {
167   // Limits: GL_MAX_VARYING_COMPONENTS, GL_MAX_TEXTURE_IMAGE_UNITS,
168   // GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
169   // clang-format off
170   const GLchar *shader_preamble = "#version 300 es\n#define LAYER_COUNT ";
171 
172   const GLchar *vertex_shader_source =
173 "\n"
174 "precision mediump int;                                                     \n"
175 "uniform vec4 uViewport;                                                    \n"
176 "uniform sampler2D uLayerTextures[LAYER_COUNT];                             \n"
177 "uniform vec4 uLayerCrop[LAYER_COUNT];                                      \n"
178 "in vec2 vPosition;                                                         \n"
179 "in vec2 vTexCoords;                                                        \n"
180 "out vec2 fTexCoords[LAYER_COUNT];                                          \n"
181 "void main() {                                                              \n"
182 "  for (int i = 0; i < LAYER_COUNT; i++) {                                  \n"
183 "    fTexCoords[i] = (uLayerCrop[i].xy + vTexCoords * uLayerCrop[i].zw) /   \n"
184 "                     vec2(textureSize(uLayerTextures[i], 0));              \n"
185 "  }                                                                        \n"
186 "  vec2 scaledPosition = uViewport.xy + vPosition * uViewport.zw;           \n"
187 "  gl_Position = vec4(scaledPosition * vec2(2.0) - vec2(1.0), 0.0, 1.0);    \n"
188 "}                                                                          \n";
189 
190   const GLchar *fragment_shader_source =
191 "\n"
192 "precision mediump float;                                                   \n"
193 "uniform sampler2D uLayerTextures[LAYER_COUNT];                             \n"
194 "uniform float uLayerAlpha[LAYER_COUNT];                                    \n"
195 "in vec2 fTexCoords[LAYER_COUNT];                                           \n"
196 "out vec4 oFragColor;                                                       \n"
197 "void main() {                                                              \n"
198 "  vec3 color = vec3(0.0, 0.0, 0.0);                                        \n"
199 "  float alphaCover = 1.0;                                                  \n"
200 "  for (int i = 0; i < LAYER_COUNT; i++) {                                  \n"
201 "    vec4 texSample = texture(uLayerTextures[i], fTexCoords[i]);            \n"
202 "    float a = texSample.a * uLayerAlpha[i];                                \n"
203 "    color += a * alphaCover * texSample.rgb;                               \n"
204 "    alphaCover *= 1.0 - a;                                                 \n"
205 "    if (alphaCover <= 0.5/255.0)                                           \n"
206 "      break;                                                               \n"
207 "  }                                                                        \n"
208 "  oFragColor = vec4(color, 1.0 - alphaCover);                              \n"
209 "}                                                                          \n";
210   // clang-format on
211 
212   int i, ret = 1;
213   GLint max_texture_images, status;
214   AutoGLShader vertex_shader, fragment_shader;
215   AutoGLProgram program;
216   std::string shader_log;
217 
218   glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_images);
219 
220   for (i = 1; i <= max_texture_images; i++) {
221     std::ostringstream layer_count_formatter;
222     layer_count_formatter << i;
223     std::string layer_count(layer_count_formatter.str());
224     const GLchar *shader_sources[3] = {shader_preamble, layer_count.c_str(),
225                                        NULL};
226 
227     shader_sources[2] = vertex_shader_source;
228     vertex_shader = CompileAndCheckShader(GL_VERTEX_SHADER, 3, shader_sources,
229                                           ret ? &shader_log : NULL);
230     if (!vertex_shader.get()) {
231       if (ret)
232         ALOGE("Failed to make vertex shader:\n%s", shader_log.c_str());
233       break;
234     }
235 
236     shader_sources[2] = fragment_shader_source;
237     fragment_shader = CompileAndCheckShader(
238         GL_FRAGMENT_SHADER, 3, shader_sources, ret ? &shader_log : NULL);
239     if (!fragment_shader.get()) {
240       if (ret)
241         ALOGE("Failed to make fragment shader:\n%s", shader_log.c_str());
242       break;
243     }
244 
245     program = AutoGLProgram(glCreateProgram());
246     if (!program.get()) {
247       if (ret)
248         ALOGE("Failed to create program %s", GetGLError());
249       break;
250     }
251 
252     glAttachShader(program.get(), vertex_shader.get());
253     glAttachShader(program.get(), fragment_shader.get());
254     glBindAttribLocation(program.get(), 0, "vPosition");
255     glBindAttribLocation(program.get(), 1, "vTexCoords");
256     glLinkProgram(program.get());
257     glDetachShader(program.get(), vertex_shader.get());
258     glDetachShader(program.get(), fragment_shader.get());
259 
260     glGetProgramiv(program.get(), GL_LINK_STATUS, &status);
261     if (!status) {
262       if (ret) {
263         GLint log_length;
264         glGetProgramiv(program.get(), GL_INFO_LOG_LENGTH, &log_length);
265         std::string program_log(log_length, ' ');
266         glGetProgramInfoLog(program.get(), log_length, NULL, &program_log[0]);
267         ALOGE("Failed to link program: \n%s", program_log.c_str());
268       }
269       break;
270     }
271 
272     ret = 0;
273     blend_programs->emplace_back(std::move(program));
274   }
275 
276   return ret;
277 }
278 
279 struct RenderingCommand {
280   struct TextureSource {
281     unsigned texture_index;
282     float crop_bounds[4];
283     float alpha;
284   };
285 
286   float bounds[4];
287   unsigned texture_count;
288   TextureSource textures[MAX_OVERLAPPING_LAYERS];
289 
RenderingCommandandroid::RenderingCommand290   RenderingCommand() : texture_count(0) {
291   }
292 };
293 
ConstructCommands(const hwc_layer_1 * layers,size_t num_layers,std::vector<RenderingCommand> * commands)294 static void ConstructCommands(const hwc_layer_1 *layers, size_t num_layers,
295                               std::vector<RenderingCommand> *commands) {
296   std::vector<FRect> in_rects;
297   std::vector<FRectSet> out_rects;
298   int i;
299 
300   for (unsigned rect_index = 0; rect_index < num_layers; rect_index++) {
301     const hwc_layer_1 &layer = layers[rect_index];
302     FRect rect;
303     in_rects.push_back(FRect(layer.displayFrame.left, layer.displayFrame.top,
304                              layer.displayFrame.right,
305                              layer.displayFrame.bottom));
306   }
307 
308   seperate_frects_64(in_rects, &out_rects);
309 
310   for (unsigned rect_index = 0; rect_index < out_rects.size(); rect_index++) {
311     const FRectSet &out_rect = out_rects[rect_index];
312     commands->push_back(RenderingCommand());
313     RenderingCommand &cmd = commands->back();
314 
315     memcpy(cmd.bounds, out_rect.rect.bounds, sizeof(cmd.bounds));
316 
317     uint64_t tex_set = out_rect.id_set.getBits();
318     for (unsigned i = num_layers - 1; tex_set != 0x0; i--) {
319       if (tex_set & (0x1 << i)) {
320         tex_set &= ~(0x1 << i);
321 
322         const hwc_layer_1 &layer = layers[i];
323 
324         FRect display_rect(layer.displayFrame.left, layer.displayFrame.top,
325                            layer.displayFrame.right, layer.displayFrame.bottom);
326         float display_size[2] = {
327             display_rect.bounds[2] - display_rect.bounds[0],
328             display_rect.bounds[3] - display_rect.bounds[1]};
329 
330         FRect crop_rect(layer.sourceCropf.left, layer.sourceCropf.top,
331                         layer.sourceCropf.right, layer.sourceCropf.bottom);
332         float crop_size[2] = {crop_rect.bounds[2] - crop_rect.bounds[0],
333                               crop_rect.bounds[3] - crop_rect.bounds[1]};
334 
335         RenderingCommand::TextureSource &src = cmd.textures[cmd.texture_count];
336         cmd.texture_count++;
337         src.texture_index = i;
338 
339         for (int b = 0; b < 4; b++) {
340           float bound_percent = (cmd.bounds[b] - display_rect.bounds[b % 2]) /
341                                 display_size[b % 2];
342           src.crop_bounds[b] =
343               crop_rect.bounds[b % 2] + bound_percent * crop_size[b % 2];
344         }
345 
346         if (layer.blending == HWC_BLENDING_NONE) {
347           src.alpha = 1.0f;
348           // This layer is opaque. There is no point in using layers below this
349           // one.
350           break;
351         }
352 
353         src.alpha = layer.planeAlpha / 255.0f;
354       }
355     }
356   }
357 }
358 
EGLFenceWait(EGLDisplay egl_display,int acquireFenceFd)359 static int EGLFenceWait(EGLDisplay egl_display, int acquireFenceFd) {
360   int ret = 0;
361 
362   EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, acquireFenceFd,
363                       EGL_NONE};
364   EGLSyncKHR egl_sync =
365       eglCreateSyncKHR(egl_display, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
366   if (egl_sync == EGL_NO_SYNC_KHR) {
367     ALOGE("Failed to make EGLSyncKHR from acquireFenceFd: %s", GetEGLError());
368     close(acquireFenceFd);
369     return 1;
370   }
371 
372   EGLint success = eglWaitSyncKHR(egl_display, egl_sync, 0);
373   if (success == EGL_FALSE) {
374     ALOGE("Failed to wait for acquire: %s", GetEGLError());
375     ret = 1;
376   }
377   eglDestroySyncKHR(egl_display, egl_sync);
378 
379   return ret;
380 }
381 
CreateTextureFromHandle(EGLDisplay egl_display,buffer_handle_t handle,AutoEGLImageAndGLTexture * out)382 static int CreateTextureFromHandle(EGLDisplay egl_display,
383                                    buffer_handle_t handle,
384                                    AutoEGLImageAndGLTexture *out) {
385   EGLImageKHR image = eglCreateImageKHR(
386       egl_display, EGL_NO_CONTEXT, EGL_NATIVE_HANDLE_ANDROID_NVX,
387       (EGLClientBuffer)handle, NULL /* no attribs */);
388 
389   if (image == EGL_NO_IMAGE_KHR) {
390     ALOGE("Failed to make image %s %p", GetEGLError(), handle);
391     return -EINVAL;
392   }
393 
394   GLuint texture;
395   glGenTextures(1, &texture);
396   glBindTexture(GL_TEXTURE_2D, texture);
397   glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)image);
398   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
399   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
400   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
401   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
402   glBindTexture(GL_TEXTURE_2D, 0);
403 
404   out->image.reset(image);
405   out->texture.reset(texture);
406 
407   return 0;
408 }
409 
Compositor()410 GLWorker::Compositor::Compositor()
411     : egl_display_(EGL_NO_DISPLAY), egl_ctx_(EGL_NO_CONTEXT) {
412 }
413 
Init()414 int GLWorker::Compositor::Init() {
415   int ret = 0;
416   const char *egl_extensions;
417   const char *gl_extensions;
418   EGLint num_configs;
419   EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE, EGL_NONE};
420   EGLConfig egl_config;
421 
422   // clang-format off
423   const GLfloat verts[] = {
424     0.0f,  0.0f,    0.0f, 0.0f,
425     0.0f,  2.0f,    0.0f, 2.0f,
426     2.0f,  0.0f,    2.0f, 0.0f
427   };
428   // clang-format on
429 
430   const EGLint config_attribs[] = {EGL_RENDERABLE_TYPE,
431                                    EGL_OPENGL_ES2_BIT,
432                                    EGL_RED_SIZE,
433                                    8,
434                                    EGL_GREEN_SIZE,
435                                    8,
436                                    EGL_BLUE_SIZE,
437                                    8,
438                                    EGL_NONE};
439 
440   const EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
441 
442   egl_display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
443   if (egl_display_ == EGL_NO_DISPLAY) {
444     ALOGE("Failed to get egl display");
445     return 1;
446   }
447 
448   if (!eglInitialize(egl_display_, NULL, NULL)) {
449     ALOGE("Failed to initialize egl: %s", GetEGLError());
450     return 1;
451   }
452 
453   egl_extensions = eglQueryString(egl_display_, EGL_EXTENSIONS);
454 
455   // These extensions are all technically required but not always reported due
456   // to meta EGL filtering them out.
457   if (!HasExtension("EGL_KHR_image_base", egl_extensions))
458     ALOGW("EGL_KHR_image_base extension not supported");
459 
460   if (!HasExtension("EGL_ANDROID_image_native_buffer", egl_extensions))
461     ALOGW("EGL_ANDROID_image_native_buffer extension not supported");
462 
463   if (!HasExtension("EGL_ANDROID_native_fence_sync", egl_extensions))
464     ALOGW("EGL_ANDROID_native_fence_sync extension not supported");
465 
466   if (!eglChooseConfig(egl_display_, config_attribs, &egl_config, 1,
467                        &num_configs)) {
468     ALOGE("eglChooseConfig() failed with error: %s", GetEGLError());
469     return 1;
470   }
471 
472   egl_ctx_ =
473       eglCreateContext(egl_display_, egl_config,
474                        EGL_NO_CONTEXT /* No shared context */, context_attribs);
475 
476   if (egl_ctx_ == EGL_NO_CONTEXT) {
477     ALOGE("Failed to create OpenGL ES Context: %s", GetEGLError());
478     return 1;
479   }
480 
481   if (!eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_ctx_)) {
482     ALOGE("Failed to make the OpenGL ES Context current: %s", GetEGLError());
483     return 1;
484   }
485 
486   gl_extensions = (const char *)glGetString(GL_EXTENSIONS);
487 
488   if (!HasExtension("GL_OES_EGL_image", gl_extensions))
489     ALOGW("GL_OES_EGL_image extension not supported");
490 
491   GLuint vertex_buffer;
492   glGenBuffers(1, &vertex_buffer);
493   glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
494   glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
495   glBindBuffer(GL_ARRAY_BUFFER, 0);
496   vertex_buffer_.reset(vertex_buffer);
497 
498   if (GenerateShaders(&blend_programs_)) {
499     return 1;
500   }
501 
502   return 0;
503 }
504 
~Compositor()505 GLWorker::Compositor::~Compositor() {
506   if (egl_display_ != EGL_NO_DISPLAY && egl_ctx_ != EGL_NO_CONTEXT)
507     if (eglDestroyContext(egl_display_, egl_ctx_) == EGL_FALSE)
508       ALOGE("Failed to destroy OpenGL ES Context: %s", GetEGLError());
509 }
510 
Composite(hwc_layer_1 * layers,size_t num_layers,sp<GraphicBuffer> framebuffer)511 int GLWorker::Compositor::Composite(hwc_layer_1 *layers, size_t num_layers,
512                                     sp<GraphicBuffer> framebuffer) {
513   ATRACE_CALL();
514   int ret = 0;
515   size_t i;
516   std::vector<AutoEGLImageAndGLTexture> layer_textures;
517   std::vector<RenderingCommand> commands;
518 
519   if (num_layers == 0) {
520     return -EALREADY;
521   }
522 
523   GLint frame_width = framebuffer->getWidth();
524   GLint frame_height = framebuffer->getHeight();
525   EGLSyncKHR finished_sync;
526 
527   AutoEGLImageKHR egl_fb_image(
528       eglCreateImageKHR(egl_display_, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
529                         (EGLClientBuffer)framebuffer->getNativeBuffer(),
530                         NULL /* no attribs */),
531       EGLImageDeleter(egl_display_));
532 
533   if (egl_fb_image.get() == EGL_NO_IMAGE_KHR) {
534     ALOGE("Failed to make image from target buffer: %s", GetEGLError());
535     return -EINVAL;
536   }
537 
538   GLuint gl_fb_tex;
539   glGenTextures(1, &gl_fb_tex);
540   AutoGLTexture gl_fb_tex_auto(gl_fb_tex);
541   glBindTexture(GL_TEXTURE_2D, gl_fb_tex);
542   glEGLImageTargetTexture2DOES(GL_TEXTURE_2D,
543                                (GLeglImageOES)egl_fb_image.get());
544   glBindTexture(GL_TEXTURE_2D, 0);
545 
546   GLuint gl_fb;
547   glGenFramebuffers(1, &gl_fb);
548   AutoGLFramebuffer gl_fb_auto(gl_fb);
549   glBindFramebuffer(GL_FRAMEBUFFER, gl_fb);
550   glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
551                          gl_fb_tex, 0);
552 
553   if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
554     ALOGE("Failed framebuffer check for created target buffer: %s",
555           GetGLFramebufferError());
556     return -EINVAL;
557   }
558 
559   for (i = 0; i < num_layers; i++) {
560     const struct hwc_layer_1 *layer = &layers[i];
561 
562     if (ret) {
563       if (layer->acquireFenceFd >= 0)
564         close(layer->acquireFenceFd);
565       continue;
566     }
567 
568     layer_textures.emplace_back(egl_display_);
569     ret = CreateTextureFromHandle(egl_display_, layer->handle,
570                                   &layer_textures.back());
571     if (!ret) {
572       ret = EGLFenceWait(egl_display_, layer->acquireFenceFd);
573     }
574     if (ret) {
575       layer_textures.pop_back();
576       ret = -EINVAL;
577     }
578   }
579 
580   if (ret)
581     return ret;
582 
583   ConstructCommands(layers, num_layers, &commands);
584 
585   glViewport(0, 0, frame_width, frame_height);
586 
587   glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
588   glClear(GL_COLOR_BUFFER_BIT);
589 
590   glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_.get());
591   glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, NULL);
592   glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4,
593                         (void *)(sizeof(float) * 2));
594   glEnableVertexAttribArray(0);
595   glEnableVertexAttribArray(1);
596   glEnable(GL_SCISSOR_TEST);
597 
598   for (const RenderingCommand &cmd : commands) {
599     if (cmd.texture_count <= 0) {
600       continue;
601     }
602 
603     // TODO(zachr): handle the case of too many overlapping textures for one
604     // area by falling back to rendering as many layers as possible using
605     // multiple blending passes.
606     if (cmd.texture_count > blend_programs_.size()) {
607       ALOGE("Too many layers to render in one area");
608       continue;
609     }
610 
611     GLint program = blend_programs_[cmd.texture_count - 1].get();
612     glUseProgram(program);
613     GLint gl_viewport_loc = glGetUniformLocation(program, "uViewport");
614     GLint gl_tex_loc = glGetUniformLocation(program, "uLayerTextures");
615     GLint gl_crop_loc = glGetUniformLocation(program, "uLayerCrop");
616     GLint gl_alpha_loc = glGetUniformLocation(program, "uLayerAlpha");
617     glUniform4f(gl_viewport_loc, cmd.bounds[0] / (float)frame_width,
618                 cmd.bounds[1] / (float)frame_height,
619                 (cmd.bounds[2] - cmd.bounds[0]) / (float)frame_width,
620                 (cmd.bounds[3] - cmd.bounds[1]) / (float)frame_height);
621 
622     for (unsigned src_index = 0; src_index < cmd.texture_count; src_index++) {
623       const RenderingCommand::TextureSource &src = cmd.textures[src_index];
624       glUniform1f(gl_alpha_loc + src_index, src.alpha);
625       glUniform4f(gl_crop_loc + src_index, src.crop_bounds[0],
626                   src.crop_bounds[1], src.crop_bounds[2] - src.crop_bounds[0],
627                   src.crop_bounds[3] - src.crop_bounds[1]);
628 
629       glUniform1i(gl_tex_loc + src_index, src_index);
630       glActiveTexture(GL_TEXTURE0 + src_index);
631       glBindTexture(GL_TEXTURE_2D,
632                     layer_textures[src.texture_index].texture.get());
633     }
634 
635     glScissor(cmd.bounds[0], cmd.bounds[1], cmd.bounds[2] - cmd.bounds[0],
636               cmd.bounds[3] - cmd.bounds[1]);
637     glDrawArrays(GL_TRIANGLES, 0, 3);
638 
639     for (unsigned src_index = 0; src_index < cmd.texture_count; src_index++) {
640       glActiveTexture(GL_TEXTURE0 + src_index);
641       glBindTexture(GL_TEXTURE_2D, 0);
642     }
643   }
644 
645   glDisable(GL_SCISSOR_TEST);
646   glActiveTexture(GL_TEXTURE0);
647   glDisableVertexAttribArray(0);
648   glDisableVertexAttribArray(1);
649   glBindBuffer(GL_ARRAY_BUFFER, 0);
650   glUseProgram(0);
651 
652   glBindFramebuffer(GL_FRAMEBUFFER, 0);
653 
654   return ret;
655 }
656 
DoComposition(Compositor & compositor,Work * work)657 int GLWorker::DoComposition(Compositor &compositor, Work *work) {
658   int ret =
659       compositor.Composite(work->layers, work->num_layers, work->framebuffer);
660 
661   int timeline_fd = work->timeline_fd;
662   work->timeline_fd = -1;
663 
664   if (ret) {
665     worker_ret_ = ret;
666     glFinish();
667     sw_sync_timeline_inc(timeline_fd, work->num_layers);
668     close(timeline_fd);
669     return pthread_cond_signal(&work_done_cond_);
670   }
671 
672   unsigned timeline_count = work->num_layers + 1;
673   worker_ret_ = sw_sync_fence_create(timeline_fd, "GLComposition done fence",
674                                      timeline_count);
675   ret = pthread_cond_signal(&work_done_cond_);
676 
677   glFinish();
678 
679   sw_sync_timeline_inc(timeline_fd, timeline_count);
680   close(timeline_fd);
681 
682   return ret;
683 }
684 
GLWorker()685 GLWorker::GLWorker() : initialized_(false) {
686 }
687 
~GLWorker()688 GLWorker::~GLWorker() {
689   if (!initialized_)
690     return;
691 
692   if (SignalWorker(NULL, true) != 0 || pthread_join(thread_, NULL) != 0)
693     pthread_kill(thread_, SIGTERM);
694 
695   pthread_cond_destroy(&work_ready_cond_);
696   pthread_cond_destroy(&work_done_cond_);
697   pthread_mutex_destroy(&lock_);
698 }
699 
700 #define TRY(x, n, g)                  \
701   ret = x;                            \
702   if (ret) {                          \
703     ALOGE("Failed to " n " %d", ret); \
704     g;                                \
705   }
706 
707 #define TRY_RETURN(x, n) TRY(x, n, return ret)
708 
Init()709 int GLWorker::Init() {
710   int ret = 0;
711 
712   worker_work_ = NULL;
713   worker_exit_ = false;
714   worker_ret_ = -1;
715 
716   ret = pthread_cond_init(&work_ready_cond_, NULL);
717   if (ret) {
718     ALOGE("Failed to int GLThread condition %d", ret);
719     return ret;
720   }
721 
722   ret = pthread_cond_init(&work_done_cond_, NULL);
723   if (ret) {
724     ALOGE("Failed to int GLThread condition %d", ret);
725     pthread_cond_destroy(&work_ready_cond_);
726     return ret;
727   }
728 
729   ret = pthread_mutex_init(&lock_, NULL);
730   if (ret) {
731     ALOGE("Failed to init GLThread lock %d", ret);
732     pthread_cond_destroy(&work_ready_cond_);
733     pthread_cond_destroy(&work_done_cond_);
734     return ret;
735   }
736 
737   ret = pthread_create(&thread_, NULL, StartRoutine, this);
738   if (ret) {
739     ALOGE("Failed to create GLThread %d", ret);
740     pthread_cond_destroy(&work_ready_cond_);
741     pthread_cond_destroy(&work_done_cond_);
742     pthread_mutex_destroy(&lock_);
743     return ret;
744   }
745 
746   initialized_ = true;
747 
748   TRY_RETURN(pthread_mutex_lock(&lock_), "lock GLThread");
749 
750   while (!worker_exit_ && worker_ret_ != 0)
751     TRY(pthread_cond_wait(&work_done_cond_, &lock_), "wait on condition",
752         goto out_unlock);
753 
754   ret = worker_ret_;
755 
756 out_unlock:
757   int unlock_ret = pthread_mutex_unlock(&lock_);
758   if (unlock_ret) {
759     ret = unlock_ret;
760     ALOGE("Failed to unlock GLThread %d", unlock_ret);
761   }
762   return ret;
763 }
764 
SignalWorker(Work * work,bool worker_exit)765 int GLWorker::SignalWorker(Work *work, bool worker_exit) {
766   int ret = 0;
767   if (worker_exit_)
768     return -EINVAL;
769   TRY_RETURN(pthread_mutex_lock(&lock_), "lock GLThread");
770   worker_work_ = work;
771   worker_exit_ = worker_exit;
772   ret = pthread_cond_signal(&work_ready_cond_);
773   if (ret) {
774     ALOGE("Failed to signal GLThread caller %d", ret);
775     pthread_mutex_unlock(&lock_);
776     return ret;
777   }
778   ret = pthread_cond_wait(&work_done_cond_, &lock_);
779   if (ret) {
780     ALOGE("Failed to wait on GLThread %d", ret);
781     pthread_mutex_unlock(&lock_);
782     return ret;
783   }
784 
785   ret = worker_ret_;
786   if (ret) {
787     pthread_mutex_unlock(&lock_);
788     return ret;
789   }
790   TRY_RETURN(pthread_mutex_unlock(&lock_), "unlock GLThread");
791   return ret;
792 }
793 
DoWork(Work * work)794 int GLWorker::DoWork(Work *work) {
795   return SignalWorker(work, false);
796 }
797 
WorkerRoutine()798 void GLWorker::WorkerRoutine() {
799   int ret = 0;
800 
801   TRY(pthread_mutex_lock(&lock_), "lock GLThread", return );
802 
803   Compositor compositor;
804 
805   TRY(compositor.Init(), "initialize GL", goto out_signal_done);
806 
807   worker_ret_ = 0;
808   TRY(pthread_cond_signal(&work_done_cond_), "signal GLThread caller",
809       goto out_signal_done);
810 
811   while (true) {
812     while (worker_work_ == NULL && !worker_exit_)
813       TRY(pthread_cond_wait(&work_ready_cond_, &lock_), "wait on condition",
814           goto out_signal_done);
815 
816     if (worker_exit_) {
817       ret = 0;
818       break;
819     }
820 
821     ret = DoComposition(compositor, worker_work_);
822 
823     worker_work_ = NULL;
824     if (ret) {
825       break;
826     }
827   }
828 
829 out_signal_done:
830   worker_exit_ = true;
831   worker_ret_ = ret;
832   TRY(pthread_cond_signal(&work_done_cond_), "signal GLThread caller",
833       goto out_unlock);
834 out_unlock:
835   TRY(pthread_mutex_unlock(&lock_), "unlock GLThread", return );
836 }
837 
838 /* static */
StartRoutine(void * arg)839 void *GLWorker::StartRoutine(void *arg) {
840   setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
841   GLWorker *worker = (GLWorker *)arg;
842   worker->WorkerRoutine();
843   return NULL;
844 }
845 
846 }  // namespace android
847