• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "hwc-gl-worker"
19 
20 #include <algorithm>
21 #include <string>
22 #include <sstream>
23 #include <unordered_set>
24 
25 #include <sys/resource.h>
26 
27 #include <cutils/properties.h>
28 
29 #include <hardware/hardware.h>
30 #include <hardware/hwcomposer.h>
31 
32 #include <ui/GraphicBuffer.h>
33 #include <ui/PixelFormat.h>
34 
35 #include <utils/Trace.h>
36 
37 #include "drmdisplaycomposition.h"
38 #include "platform.h"
39 
40 #include "glworker.h"
41 
42 #define MAX_OVERLAPPING_LAYERS 64
43 
44 namespace android {
45 
46 // clang-format off
47 // Column-major order:
48 // float mat[4] = { 1, 2, 3, 4 } ===
49 // [ 1 3 ]
50 // [ 2 4 ]
51 float kTextureTransformMatrices[] = {
52    1.0f,  0.0f,  0.0f,  1.0f, // identity matrix
53    0.0f,  1.0f,  1.0f,  0.0f, // swap x and y
54 };
55 // clang-format on
56 
GetGLError(void)57 static const char *GetGLError(void) {
58   switch (glGetError()) {
59     case GL_NO_ERROR:
60       return "GL_NO_ERROR";
61     case GL_INVALID_ENUM:
62       return "GL_INVALID_ENUM";
63     case GL_INVALID_VALUE:
64       return "GL_INVALID_VALUE";
65     case GL_INVALID_OPERATION:
66       return "GL_INVALID_OPERATION";
67     case GL_INVALID_FRAMEBUFFER_OPERATION:
68       return "GL_INVALID_FRAMEBUFFER_OPERATION";
69     case GL_OUT_OF_MEMORY:
70       return "GL_OUT_OF_MEMORY";
71     default:
72       return "Unknown error";
73   }
74 }
75 
GetGLFramebufferError(void)76 static const char *GetGLFramebufferError(void) {
77   switch (glCheckFramebufferStatus(GL_FRAMEBUFFER)) {
78     case GL_FRAMEBUFFER_COMPLETE:
79       return "GL_FRAMEBUFFER_COMPLETE";
80     case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
81       return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
82     case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
83       return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
84     case GL_FRAMEBUFFER_UNSUPPORTED:
85       return "GL_FRAMEBUFFER_UNSUPPORTED";
86     case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
87       return "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
88     default:
89       return "Unknown error";
90   }
91 }
92 
GetEGLError(void)93 static const char *GetEGLError(void) {
94   switch (eglGetError()) {
95     case EGL_SUCCESS:
96       return "EGL_SUCCESS";
97     case EGL_NOT_INITIALIZED:
98       return "EGL_NOT_INITIALIZED";
99     case EGL_BAD_ACCESS:
100       return "EGL_BAD_ACCESS";
101     case EGL_BAD_ALLOC:
102       return "EGL_BAD_ALLOC";
103     case EGL_BAD_ATTRIBUTE:
104       return "EGL_BAD_ATTRIBUTE";
105     case EGL_BAD_CONTEXT:
106       return "EGL_BAD_CONTEXT";
107     case EGL_BAD_CONFIG:
108       return "EGL_BAD_CONFIG";
109     case EGL_BAD_CURRENT_SURFACE:
110       return "EGL_BAD_CURRENT_SURFACE";
111     case EGL_BAD_DISPLAY:
112       return "EGL_BAD_DISPLAY";
113     case EGL_BAD_SURFACE:
114       return "EGL_BAD_SURFACE";
115     case EGL_BAD_MATCH:
116       return "EGL_BAD_MATCH";
117     case EGL_BAD_PARAMETER:
118       return "EGL_BAD_PARAMETER";
119     case EGL_BAD_NATIVE_PIXMAP:
120       return "EGL_BAD_NATIVE_PIXMAP";
121     case EGL_BAD_NATIVE_WINDOW:
122       return "EGL_BAD_NATIVE_WINDOW";
123     case EGL_CONTEXT_LOST:
124       return "EGL_CONTEXT_LOST";
125     default:
126       return "Unknown error";
127   }
128 }
129 
HasExtension(const char * extension,const char * extensions)130 static bool HasExtension(const char *extension, const char *extensions) {
131   const char *start, *where, *terminator;
132   start = extensions;
133   for (;;) {
134     where = (char *)strstr((const char *)start, extension);
135     if (!where)
136       break;
137     terminator = where + strlen(extension);
138     if (where == start || *(where - 1) == ' ')
139       if (*terminator == ' ' || *terminator == '\0')
140         return true;
141     start = terminator;
142   }
143   return false;
144 }
145 
CompileAndCheckShader(GLenum type,unsigned source_count,const GLchar ** sources,std::ostringstream * shader_log)146 static AutoGLShader CompileAndCheckShader(GLenum type, unsigned source_count,
147                                           const GLchar **sources,
148                                           std::ostringstream *shader_log) {
149   GLint status;
150   AutoGLShader shader(glCreateShader(type));
151   if (shader.get() == 0) {
152     if (shader_log)
153       *shader_log << "Failed glCreateShader call";
154     return 0;
155   }
156 
157   glShaderSource(shader.get(), source_count, sources, NULL);
158   glCompileShader(shader.get());
159   glGetShaderiv(shader.get(), GL_COMPILE_STATUS, &status);
160   if (!status) {
161     if (shader_log) {
162       GLint log_length;
163       glGetShaderiv(shader.get(), GL_INFO_LOG_LENGTH, &log_length);
164       std::string info_log(log_length, ' ');
165       glGetShaderInfoLog(shader.get(), log_length, NULL, &info_log.front());
166       *shader_log << "Failed to compile shader:\n" << info_log.c_str()
167                   << "\nShader Source:\n";
168       for (unsigned i = 0; i < source_count; i++) {
169         *shader_log << sources[i];
170       }
171       *shader_log << "\n";
172     }
173     return 0;
174   }
175 
176   return shader;
177 }
178 
GenerateVertexShader(int layer_count)179 static std::string GenerateVertexShader(int layer_count) {
180   std::ostringstream vertex_shader_stream;
181   vertex_shader_stream
182       << "#version 300 es\n"
183       << "#define LAYER_COUNT " << layer_count << "\n"
184       << "precision mediump int;\n"
185       << "uniform vec4 uViewport;\n"
186       << "uniform vec4 uLayerCrop[LAYER_COUNT];\n"
187       << "uniform mat2 uTexMatrix[LAYER_COUNT];\n"
188       << "in vec2 vPosition;\n"
189       << "in vec2 vTexCoords;\n"
190       << "out vec2 fTexCoords[LAYER_COUNT];\n"
191       << "void main() {\n"
192       << "  for (int i = 0; i < LAYER_COUNT; i++) {\n"
193       << "    vec2 tempCoords = vTexCoords * uTexMatrix[i];\n"
194       << "    fTexCoords[i] =\n"
195       << "        uLayerCrop[i].xy + tempCoords * uLayerCrop[i].zw;\n"
196       << "  }\n"
197       << "  vec2 scaledPosition = uViewport.xy + vPosition * uViewport.zw;\n"
198       << "  gl_Position =\n"
199       << "      vec4(scaledPosition * vec2(2.0) - vec2(1.0), 0.0, 1.0);\n"
200       << "}\n";
201   return vertex_shader_stream.str();
202 }
203 
GenerateFragmentShader(int layer_count)204 static std::string GenerateFragmentShader(int layer_count) {
205   std::ostringstream fragment_shader_stream;
206   fragment_shader_stream << "#version 300 es\n"
207                          << "#define LAYER_COUNT " << layer_count << "\n"
208                          << "#extension GL_OES_EGL_image_external : require\n"
209                          << "precision mediump float;\n";
210   for (int i = 0; i < layer_count; ++i) {
211     fragment_shader_stream << "uniform samplerExternalOES uLayerTexture" << i
212                            << ";\n";
213   }
214   fragment_shader_stream << "uniform float uLayerAlpha[LAYER_COUNT];\n"
215                          << "uniform float uLayerPremult[LAYER_COUNT];\n"
216                          << "in vec2 fTexCoords[LAYER_COUNT];\n"
217                          << "out vec4 oFragColor;\n"
218                          << "void main() {\n"
219                          << "  vec3 color = vec3(0.0, 0.0, 0.0);\n"
220                          << "  float alphaCover = 1.0;\n"
221                          << "  vec4 texSample;\n"
222                          << "  vec3 multRgb;\n";
223   for (int i = 0; i < layer_count; ++i) {
224     if (i > 0)
225       fragment_shader_stream << "  if (alphaCover > 0.5/255.0) {\n";
226     // clang-format off
227     fragment_shader_stream
228         << "  texSample = texture2D(uLayerTexture" << i << ",\n"
229         << "                        fTexCoords[" << i << "]);\n"
230         << "  multRgb = texSample.rgb *\n"
231         << "            max(texSample.a, uLayerPremult[" << i << "]);\n"
232         << "  color += multRgb * uLayerAlpha[" << i << "] * alphaCover;\n"
233         << "  alphaCover *= 1.0 - texSample.a * uLayerAlpha[" << i << "];\n";
234     // clang-format on
235   }
236   for (int i = 0; i < layer_count - 1; ++i)
237     fragment_shader_stream << "  }\n";
238   fragment_shader_stream << "  oFragColor = vec4(color, 1.0 - alphaCover);\n"
239                          << "}\n";
240   return fragment_shader_stream.str();
241 }
242 
GenerateProgram(unsigned num_textures,std::ostringstream * shader_log)243 static AutoGLProgram GenerateProgram(unsigned num_textures,
244                                      std::ostringstream *shader_log) {
245   std::string vertex_shader_string = GenerateVertexShader(num_textures);
246   const GLchar *vertex_shader_source = vertex_shader_string.c_str();
247   AutoGLShader vertex_shader = CompileAndCheckShader(
248       GL_VERTEX_SHADER, 1, &vertex_shader_source, shader_log);
249   if (!vertex_shader.get())
250     return 0;
251 
252   std::string fragment_shader_string = GenerateFragmentShader(num_textures);
253   const GLchar *fragment_shader_source = fragment_shader_string.c_str();
254   AutoGLShader fragment_shader = CompileAndCheckShader(
255       GL_FRAGMENT_SHADER, 1, &fragment_shader_source, shader_log);
256   if (!fragment_shader.get())
257     return 0;
258 
259   AutoGLProgram program(glCreateProgram());
260   if (!program.get()) {
261     if (shader_log)
262       *shader_log << "Failed to create program: " << GetGLError() << "\n";
263     return 0;
264   }
265 
266   glAttachShader(program.get(), vertex_shader.get());
267   glAttachShader(program.get(), fragment_shader.get());
268   glBindAttribLocation(program.get(), 0, "vPosition");
269   glBindAttribLocation(program.get(), 1, "vTexCoords");
270   glLinkProgram(program.get());
271   glDetachShader(program.get(), vertex_shader.get());
272   glDetachShader(program.get(), fragment_shader.get());
273 
274   GLint status;
275   glGetProgramiv(program.get(), GL_LINK_STATUS, &status);
276   if (!status) {
277     if (shader_log) {
278       GLint log_length;
279       glGetProgramiv(program.get(), GL_INFO_LOG_LENGTH, &log_length);
280       std::string program_log(log_length, ' ');
281       glGetProgramInfoLog(program.get(), log_length, NULL,
282                           &program_log.front());
283       *shader_log << "Failed to link program:\n" << program_log.c_str() << "\n";
284     }
285     return 0;
286   }
287 
288   return program;
289 }
290 
291 struct RenderingCommand {
292   struct TextureSource {
293     unsigned texture_index;
294     float crop_bounds[4];
295     float alpha;
296     float premult;
297     float texture_matrix[4];
298   };
299 
300   float bounds[4];
301   unsigned texture_count = 0;
302   TextureSource textures[MAX_OVERLAPPING_LAYERS];
303 };
304 
ConstructCommand(const DrmHwcLayer * layers,const DrmCompositionRegion & region,RenderingCommand & cmd)305 static void ConstructCommand(const DrmHwcLayer *layers,
306                              const DrmCompositionRegion &region,
307                              RenderingCommand &cmd) {
308   std::copy_n(region.frame.bounds, 4, cmd.bounds);
309 
310   for (size_t texture_index : region.source_layers) {
311     const DrmHwcLayer &layer = layers[texture_index];
312 
313     DrmHwcRect<float> display_rect(layer.display_frame);
314     float display_size[2] = {display_rect.bounds[2] - display_rect.bounds[0],
315                              display_rect.bounds[3] - display_rect.bounds[1]};
316 
317     float tex_width = layer.buffer->width;
318     float tex_height = layer.buffer->height;
319     DrmHwcRect<float> crop_rect(layer.source_crop.left / tex_width,
320                                 layer.source_crop.top / tex_height,
321                                 layer.source_crop.right / tex_width,
322                                 layer.source_crop.bottom / tex_height);
323 
324     float crop_size[2] = {crop_rect.bounds[2] - crop_rect.bounds[0],
325                           crop_rect.bounds[3] - crop_rect.bounds[1]};
326 
327     RenderingCommand::TextureSource &src = cmd.textures[cmd.texture_count];
328     cmd.texture_count++;
329     src.texture_index = texture_index;
330 
331     bool swap_xy = false;
332     bool flip_xy[2] = { false, false };
333 
334     if (layer.transform == DrmHwcTransform::kRotate180) {
335       swap_xy = false;
336       flip_xy[0] = true;
337       flip_xy[1] = true;
338     } else if (layer.transform == DrmHwcTransform::kRotate270) {
339       swap_xy = true;
340       flip_xy[0] = true;
341       flip_xy[1] = false;
342     } else if (layer.transform & DrmHwcTransform::kRotate90) {
343       swap_xy = true;
344       if (layer.transform & DrmHwcTransform::kFlipH) {
345         flip_xy[0] = true;
346         flip_xy[1] = true;
347       } else if (layer.transform & DrmHwcTransform::kFlipV) {
348         flip_xy[0] = false;
349         flip_xy[1] = false;
350       } else {
351         flip_xy[0] = false;
352         flip_xy[1] = true;
353       }
354     } else {
355       if (layer.transform & DrmHwcTransform::kFlipH)
356         flip_xy[0] = true;
357       if (layer.transform & DrmHwcTransform::kFlipV)
358         flip_xy[1] = true;
359     }
360 
361     if (swap_xy)
362       std::copy_n(&kTextureTransformMatrices[4], 4, src.texture_matrix);
363     else
364       std::copy_n(&kTextureTransformMatrices[0], 4, src.texture_matrix);
365 
366     for (int j = 0; j < 4; j++) {
367       int b = j ^ (swap_xy ? 1 : 0);
368       float bound_percent =
369           (cmd.bounds[b] - display_rect.bounds[b % 2]) / display_size[b % 2];
370       if (flip_xy[j % 2]) {
371         src.crop_bounds[j] =
372             crop_rect.bounds[j % 2 + 2] - bound_percent * crop_size[j % 2];
373       } else {
374         src.crop_bounds[j] =
375             crop_rect.bounds[j % 2] + bound_percent * crop_size[j % 2];
376       }
377     }
378 
379     if (layer.blending == DrmHwcBlending::kNone) {
380       src.alpha = src.premult = 1.0f;
381       // This layer is opaque. There is no point in using layers below this one.
382       break;
383     }
384 
385     src.alpha = layer.alpha / 255.0f;
386     src.premult = (layer.blending == DrmHwcBlending::kPreMult) ? 1.0f : 0.0f;
387   }
388 }
389 
EGLFenceWait(EGLDisplay egl_display,int acquireFenceFd)390 static int EGLFenceWait(EGLDisplay egl_display, int acquireFenceFd) {
391   int ret = 0;
392 
393   EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, acquireFenceFd,
394                       EGL_NONE};
395   EGLSyncKHR egl_sync =
396       eglCreateSyncKHR(egl_display, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
397   if (egl_sync == EGL_NO_SYNC_KHR) {
398     ALOGE("Failed to make EGLSyncKHR from acquireFenceFd: %s", GetEGLError());
399     close(acquireFenceFd);
400     return 1;
401   }
402 
403   EGLint success = eglWaitSyncKHR(egl_display, egl_sync, 0);
404   if (success == EGL_FALSE) {
405     ALOGE("Failed to wait for acquire: %s", GetEGLError());
406     ret = 1;
407   }
408   eglDestroySyncKHR(egl_display, egl_sync);
409 
410   return ret;
411 }
412 
CreateTextureFromHandle(EGLDisplay egl_display,buffer_handle_t handle,Importer * importer,AutoEGLImageAndGLTexture * out)413 static int CreateTextureFromHandle(EGLDisplay egl_display,
414                                    buffer_handle_t handle,
415                                    Importer *importer,
416                                    AutoEGLImageAndGLTexture *out) {
417   EGLImageKHR image = importer->ImportImage(egl_display, handle);
418 
419   if (image == EGL_NO_IMAGE_KHR) {
420     ALOGE("Failed to make image %s %p", GetEGLError(), handle);
421     return -EINVAL;
422   }
423 
424   GLuint texture;
425   glGenTextures(1, &texture);
426   glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
427   glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, (GLeglImageOES)image);
428   glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
429   glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
430   glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_REPEAT);
431   glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_REPEAT);
432   glBindTexture(GL_TEXTURE_EXTERNAL_OES, 0);
433 
434   out->image.reset(egl_display, image);
435   out->texture.reset(texture);
436 
437   return 0;
438 }
439 
GLWorkerCompositor()440 GLWorkerCompositor::GLWorkerCompositor()
441     : egl_display_(EGL_NO_DISPLAY), egl_ctx_(EGL_NO_CONTEXT) {
442 }
443 
Init()444 int GLWorkerCompositor::Init() {
445   int ret = 0;
446   const char *egl_extensions;
447   const char *gl_extensions;
448   EGLint num_configs;
449   EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE, EGL_NONE};
450   EGLConfig egl_config;
451 
452   // clang-format off
453   const GLfloat verts[] = {
454     0.0f,  0.0f,    0.0f, 0.0f,
455     0.0f,  2.0f,    0.0f, 2.0f,
456     2.0f,  0.0f,    2.0f, 0.0f
457   };
458   // clang-format on
459 
460   const EGLint config_attribs[] = {EGL_RENDERABLE_TYPE,
461                                    EGL_OPENGL_ES2_BIT,
462                                    EGL_RED_SIZE,
463                                    8,
464                                    EGL_GREEN_SIZE,
465                                    8,
466                                    EGL_BLUE_SIZE,
467                                    8,
468                                    EGL_NONE};
469 
470   const EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
471 
472   egl_display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
473   if (egl_display_ == EGL_NO_DISPLAY) {
474     ALOGE("Failed to get egl display");
475     return 1;
476   }
477 
478   if (!eglInitialize(egl_display_, NULL, NULL)) {
479     ALOGE("Failed to initialize egl: %s", GetEGLError());
480     return 1;
481   }
482 
483   egl_extensions = eglQueryString(egl_display_, EGL_EXTENSIONS);
484 
485   // These extensions are all technically required but not always reported due
486   // to meta EGL filtering them out.
487   if (!HasExtension("EGL_KHR_image_base", egl_extensions))
488     ALOGW("EGL_KHR_image_base extension not supported");
489 
490   if (!HasExtension("EGL_ANDROID_image_native_buffer", egl_extensions))
491     ALOGW("EGL_ANDROID_image_native_buffer extension not supported");
492 
493   if (!HasExtension("EGL_ANDROID_native_fence_sync", egl_extensions))
494     ALOGW("EGL_ANDROID_native_fence_sync extension not supported");
495 
496   if (!eglChooseConfig(egl_display_, config_attribs, &egl_config, 1,
497                        &num_configs)) {
498     ALOGE("eglChooseConfig() failed with error: %s", GetEGLError());
499     return 1;
500   }
501 
502   egl_ctx_ =
503       eglCreateContext(egl_display_, egl_config,
504                        EGL_NO_CONTEXT /* No shared context */, context_attribs);
505 
506   if (egl_ctx_ == EGL_NO_CONTEXT) {
507     ALOGE("Failed to create OpenGL ES Context: %s", GetEGLError());
508     return 1;
509   }
510 
511   if (!eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_ctx_)) {
512     ALOGE("Failed to make the OpenGL ES Context current: %s", GetEGLError());
513     return 1;
514   }
515 
516   gl_extensions = (const char *)glGetString(GL_EXTENSIONS);
517 
518   if (!HasExtension("GL_OES_EGL_image", gl_extensions))
519     ALOGW("GL_OES_EGL_image extension not supported");
520 
521   if (!HasExtension("GL_OES_EGL_image_external", gl_extensions))
522     ALOGW("GL_OES_EGL_image_external extension not supported");
523 
524   GLuint vertex_buffer;
525   glGenBuffers(1, &vertex_buffer);
526   glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
527   glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
528   glBindBuffer(GL_ARRAY_BUFFER, 0);
529   vertex_buffer_.reset(vertex_buffer);
530 
531   std::ostringstream shader_log;
532   blend_programs_.emplace_back(GenerateProgram(1, &shader_log));
533   if (blend_programs_.back().get() == 0) {
534     ALOGE("%s", shader_log.str().c_str());
535     return 1;
536   }
537 
538   return 0;
539 }
540 
~GLWorkerCompositor()541 GLWorkerCompositor::~GLWorkerCompositor() {
542   if (egl_display_ != EGL_NO_DISPLAY && egl_ctx_ != EGL_NO_CONTEXT)
543     if (eglDestroyContext(egl_display_, egl_ctx_) == EGL_FALSE)
544       ALOGE("Failed to destroy OpenGL ES Context: %s", GetEGLError());
545 }
546 
Composite(DrmHwcLayer * layers,DrmCompositionRegion * regions,size_t num_regions,const sp<GraphicBuffer> & framebuffer,Importer * importer)547 int GLWorkerCompositor::Composite(DrmHwcLayer *layers,
548                                   DrmCompositionRegion *regions,
549                                   size_t num_regions,
550                                   const sp<GraphicBuffer> &framebuffer,
551                                   Importer *importer) {
552   ATRACE_CALL();
553   int ret = 0;
554   std::vector<AutoEGLImageAndGLTexture> layer_textures;
555   std::vector<RenderingCommand> commands;
556 
557   if (num_regions == 0) {
558     return -EALREADY;
559   }
560 
561   GLint frame_width = framebuffer->getWidth();
562   GLint frame_height = framebuffer->getHeight();
563   CachedFramebuffer *cached_framebuffer =
564       PrepareAndCacheFramebuffer(framebuffer);
565   if (cached_framebuffer == NULL) {
566     ALOGE("Composite failed because of failed framebuffer");
567     return -EINVAL;
568   }
569 
570   std::unordered_set<size_t> layers_used_indices;
571   for (size_t region_index = 0; region_index < num_regions; region_index++) {
572     DrmCompositionRegion &region = regions[region_index];
573     layers_used_indices.insert(region.source_layers.begin(),
574                                region.source_layers.end());
575     commands.emplace_back();
576     ConstructCommand(layers, region, commands.back());
577   }
578 
579   for (size_t layer_index = 0; layer_index < MAX_OVERLAPPING_LAYERS;
580        layer_index++) {
581     DrmHwcLayer *layer = &layers[layer_index];
582 
583     layer_textures.emplace_back();
584 
585     if (layers_used_indices.count(layer_index) == 0)
586       continue;
587 
588     ret = CreateTextureFromHandle(egl_display_, layer->get_usable_handle(),
589                                   importer, &layer_textures.back());
590 
591     if (!ret) {
592       ret = EGLFenceWait(egl_display_, layer->acquire_fence.Release());
593     }
594     if (ret) {
595       layer_textures.pop_back();
596       ret = -EINVAL;
597     }
598   }
599 
600   if (ret)
601     return ret;
602 
603   glViewport(0, 0, frame_width, frame_height);
604 
605   glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
606   glClear(GL_COLOR_BUFFER_BIT);
607 
608   glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_.get());
609   glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, NULL);
610   glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4,
611                         (void *)(sizeof(float) * 2));
612   glEnableVertexAttribArray(0);
613   glEnableVertexAttribArray(1);
614   glEnable(GL_SCISSOR_TEST);
615 
616   for (const RenderingCommand &cmd : commands) {
617     if (cmd.texture_count == 0)
618       continue;
619 
620     // TODO(zachr): handle the case of too many overlapping textures for one
621     // area by falling back to rendering as many layers as possible using
622     // multiple blending passes.
623     GLint program = PrepareAndCacheProgram(cmd.texture_count);
624     if (program == 0) {
625       ALOGE("Too many layers to render in one area");
626       continue;
627     }
628 
629     glUseProgram(program);
630     GLint gl_viewport_loc = glGetUniformLocation(program, "uViewport");
631     GLint gl_crop_loc = glGetUniformLocation(program, "uLayerCrop");
632     GLint gl_alpha_loc = glGetUniformLocation(program, "uLayerAlpha");
633     GLint gl_premult_loc = glGetUniformLocation(program, "uLayerPremult");
634     GLint gl_tex_matrix_loc = glGetUniformLocation(program, "uTexMatrix");
635     glUniform4f(gl_viewport_loc, cmd.bounds[0] / (float)frame_width,
636                 cmd.bounds[1] / (float)frame_height,
637                 (cmd.bounds[2] - cmd.bounds[0]) / (float)frame_width,
638                 (cmd.bounds[3] - cmd.bounds[1]) / (float)frame_height);
639 
640     for (unsigned src_index = 0; src_index < cmd.texture_count; src_index++) {
641       std::ostringstream texture_name_formatter;
642       texture_name_formatter << "uLayerTexture" << src_index;
643       GLint gl_tex_loc =
644           glGetUniformLocation(program, texture_name_formatter.str().c_str());
645 
646       const RenderingCommand::TextureSource &src = cmd.textures[src_index];
647       glUniform1f(gl_alpha_loc + src_index, src.alpha);
648       glUniform1f(gl_premult_loc + src_index, src.premult);
649       glUniform4f(gl_crop_loc + src_index, src.crop_bounds[0],
650                   src.crop_bounds[1], src.crop_bounds[2] - src.crop_bounds[0],
651                   src.crop_bounds[3] - src.crop_bounds[1]);
652       glUniform1i(gl_tex_loc, src_index);
653       glUniformMatrix2fv(gl_tex_matrix_loc + src_index, 1, GL_FALSE,
654                          src.texture_matrix);
655       glActiveTexture(GL_TEXTURE0 + src_index);
656       glBindTexture(GL_TEXTURE_EXTERNAL_OES,
657                     layer_textures[src.texture_index].texture.get());
658     }
659 
660     glScissor(cmd.bounds[0], cmd.bounds[1], cmd.bounds[2] - cmd.bounds[0],
661               cmd.bounds[3] - cmd.bounds[1]);
662     glDrawArrays(GL_TRIANGLES, 0, 3);
663 
664     for (unsigned src_index = 0; src_index < cmd.texture_count; src_index++) {
665       glActiveTexture(GL_TEXTURE0 + src_index);
666       glBindTexture(GL_TEXTURE_EXTERNAL_OES, 0);
667     }
668   }
669 
670   glDisable(GL_SCISSOR_TEST);
671   glActiveTexture(GL_TEXTURE0);
672   glDisableVertexAttribArray(0);
673   glDisableVertexAttribArray(1);
674   glBindBuffer(GL_ARRAY_BUFFER, 0);
675   glUseProgram(0);
676 
677   glBindFramebuffer(GL_FRAMEBUFFER, 0);
678 
679   return ret;
680 }
681 
Finish()682 void GLWorkerCompositor::Finish() {
683   ATRACE_CALL();
684   glFinish();
685 
686   char use_framebuffer_cache_opt[PROPERTY_VALUE_MAX];
687   property_get("hwc.drm.use_framebuffer_cache", use_framebuffer_cache_opt, "1");
688   bool use_framebuffer_cache = atoi(use_framebuffer_cache_opt);
689 
690   if (use_framebuffer_cache) {
691     for (auto &fb : cached_framebuffers_)
692       fb.strong_framebuffer.clear();
693   } else {
694     cached_framebuffers_.clear();
695   }
696 }
697 
CachedFramebuffer(const sp<GraphicBuffer> & gb,AutoEGLDisplayImage && image,AutoGLTexture && tex,AutoGLFramebuffer && fb)698 GLWorkerCompositor::CachedFramebuffer::CachedFramebuffer(
699     const sp<GraphicBuffer> &gb, AutoEGLDisplayImage &&image,
700     AutoGLTexture &&tex, AutoGLFramebuffer &&fb)
701     : strong_framebuffer(gb),
702       weak_framebuffer(gb),
703       egl_fb_image(std::move(image)),
704       gl_fb_tex(std::move(tex)),
705       gl_fb(std::move(fb)) {
706 }
707 
Promote()708 bool GLWorkerCompositor::CachedFramebuffer::Promote() {
709   if (strong_framebuffer.get() != NULL)
710     return true;
711   strong_framebuffer = weak_framebuffer.promote();
712   return strong_framebuffer.get() != NULL;
713 }
714 
715 GLWorkerCompositor::CachedFramebuffer *
FindCachedFramebuffer(const sp<GraphicBuffer> & framebuffer)716 GLWorkerCompositor::FindCachedFramebuffer(
717     const sp<GraphicBuffer> &framebuffer) {
718   for (auto &fb : cached_framebuffers_)
719     if (fb.weak_framebuffer == framebuffer)
720       return &fb;
721   return NULL;
722 }
723 
724 GLWorkerCompositor::CachedFramebuffer *
PrepareAndCacheFramebuffer(const sp<GraphicBuffer> & framebuffer)725 GLWorkerCompositor::PrepareAndCacheFramebuffer(
726     const sp<GraphicBuffer> &framebuffer) {
727   CachedFramebuffer *cached_framebuffer = FindCachedFramebuffer(framebuffer);
728   if (cached_framebuffer != NULL) {
729     if (cached_framebuffer->Promote()) {
730       glBindFramebuffer(GL_FRAMEBUFFER, cached_framebuffer->gl_fb.get());
731       return cached_framebuffer;
732     }
733 
734     for (auto it = cached_framebuffers_.begin();
735          it != cached_framebuffers_.end(); ++it) {
736       if (it->weak_framebuffer == framebuffer) {
737         cached_framebuffers_.erase(it);
738         break;
739       }
740     }
741   }
742 
743   AutoEGLDisplayImage egl_fb_image(
744       egl_display_,
745       eglCreateImageKHR(egl_display_, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
746                         (EGLClientBuffer)framebuffer->getNativeBuffer(),
747                         NULL /* no attribs */));
748 
749   if (egl_fb_image.image() == EGL_NO_IMAGE_KHR) {
750     ALOGE("Failed to make image from target buffer: %s", GetEGLError());
751     return NULL;
752   }
753 
754   GLuint gl_fb_tex;
755   glGenTextures(1, &gl_fb_tex);
756   AutoGLTexture gl_fb_tex_auto(gl_fb_tex);
757   glBindTexture(GL_TEXTURE_2D, gl_fb_tex);
758   glEGLImageTargetTexture2DOES(GL_TEXTURE_2D,
759                                (GLeglImageOES)egl_fb_image.image());
760   glBindTexture(GL_TEXTURE_2D, 0);
761 
762   GLuint gl_fb;
763   glGenFramebuffers(1, &gl_fb);
764   AutoGLFramebuffer gl_fb_auto(gl_fb);
765   glBindFramebuffer(GL_FRAMEBUFFER, gl_fb);
766   glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
767                          gl_fb_tex, 0);
768 
769   if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
770     ALOGE("Failed framebuffer check for created target buffer: %s",
771           GetGLFramebufferError());
772     return NULL;
773   }
774 
775   cached_framebuffers_.emplace_back(framebuffer, std::move(egl_fb_image),
776                                     std::move(gl_fb_tex_auto),
777                                     std::move(gl_fb_auto));
778   return &cached_framebuffers_.back();
779 }
780 
PrepareAndCacheProgram(unsigned texture_count)781 GLint GLWorkerCompositor::PrepareAndCacheProgram(unsigned texture_count) {
782   if (blend_programs_.size() >= texture_count) {
783     GLint program = blend_programs_[texture_count - 1].get();
784     if (program != 0)
785       return program;
786   }
787 
788   AutoGLProgram program = GenerateProgram(texture_count, NULL);
789   if (program.get() != 0) {
790     if (blend_programs_.size() < texture_count)
791       blend_programs_.resize(texture_count);
792     blend_programs_[texture_count - 1] = std::move(program);
793     return blend_programs_[texture_count - 1].get();
794   }
795 
796   return 0;
797 }
798 
799 }  // namespace android
800