1 /*
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 
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18 
19 #include "ProgramCache.h"
20 
21 #include <GLES2/gl2.h>
22 #include <GLES2/gl2ext.h>
23 #include <log/log.h>
24 #include <renderengine/private/Description.h>
25 #include <utils/String8.h>
26 #include <utils/Trace.h>
27 #include "Program.h"
28 
29 ANDROID_SINGLETON_STATIC_INSTANCE(android::renderengine::gl::ProgramCache)
30 
31 namespace android {
32 namespace renderengine {
33 namespace gl {
34 
35 /*
36  * A simple formatter class to automatically add the endl and
37  * manage the indentation.
38  */
39 
40 class Formatter;
41 static Formatter& indent(Formatter& f);
42 static Formatter& dedent(Formatter& f);
43 
44 class Formatter {
45     String8 mString;
46     int mIndent;
47     typedef Formatter& (*FormaterManipFunc)(Formatter&);
48     friend Formatter& indent(Formatter& f);
49     friend Formatter& dedent(Formatter& f);
50 
51 public:
Formatter()52     Formatter() : mIndent(0) {}
53 
getString() const54     String8 getString() const { return mString; }
55 
operator <<(Formatter & out,const char * in)56     friend Formatter& operator<<(Formatter& out, const char* in) {
57         for (int i = 0; i < out.mIndent; i++) {
58             out.mString.append("    ");
59         }
60         out.mString.append(in);
61         out.mString.append("\n");
62         return out;
63     }
operator <<(Formatter & out,const String8 & in)64     friend inline Formatter& operator<<(Formatter& out, const String8& in) {
65         return operator<<(out, in.string());
66     }
operator <<(Formatter & to,FormaterManipFunc func)67     friend inline Formatter& operator<<(Formatter& to, FormaterManipFunc func) {
68         return (*func)(to);
69     }
70 };
indent(Formatter & f)71 Formatter& indent(Formatter& f) {
72     f.mIndent++;
73     return f;
74 }
dedent(Formatter & f)75 Formatter& dedent(Formatter& f) {
76     f.mIndent--;
77     return f;
78 }
79 
primeCache(EGLContext context,bool useColorManagement,bool toneMapperShaderOnly)80 void ProgramCache::primeCache(
81         EGLContext context, bool useColorManagement, bool toneMapperShaderOnly) {
82     auto& cache = mCaches[context];
83     uint32_t shaderCount = 0;
84 
85     if (toneMapperShaderOnly) {
86         Key shaderKey;
87         // base settings used by HDR->SDR tonemap only
88         shaderKey.set(Key::BLEND_MASK | Key::INPUT_TRANSFORM_MATRIX_MASK |
89                       Key::OUTPUT_TRANSFORM_MATRIX_MASK | Key::OUTPUT_TF_MASK |
90                       Key::OPACITY_MASK | Key::ALPHA_MASK |
91                       Key::ROUNDED_CORNERS_MASK | Key::TEXTURE_MASK,
92                       Key::BLEND_NORMAL | Key::INPUT_TRANSFORM_MATRIX_ON |
93                       Key::OUTPUT_TRANSFORM_MATRIX_ON | Key::OUTPUT_TF_SRGB |
94                       Key::OPACITY_OPAQUE | Key::ALPHA_EQ_ONE |
95                       Key::ROUNDED_CORNERS_OFF | Key::TEXTURE_EXT);
96         for (int i = 0; i < 4; i++) {
97             // Cache input transfer for HLG & ST2084
98             shaderKey.set(Key::INPUT_TF_MASK, (i & 1) ?
99                     Key::INPUT_TF_HLG : Key::INPUT_TF_ST2084);
100 
101             // Cache Y410 input on or off
102             shaderKey.set(Key::Y410_BT2020_MASK, (i & 2) ?
103                     Key::Y410_BT2020_ON : Key::Y410_BT2020_OFF);
104             if (cache.count(shaderKey) == 0) {
105                 cache.emplace(shaderKey, generateProgram(shaderKey));
106                 shaderCount++;
107             }
108         }
109         return;
110     }
111 
112     uint32_t keyMask = Key::BLEND_MASK | Key::OPACITY_MASK | Key::ALPHA_MASK | Key::TEXTURE_MASK
113         | Key::ROUNDED_CORNERS_MASK;
114     // Prime the cache for all combinations of the above masks,
115     // leaving off the experimental color matrix mask options.
116 
117     nsecs_t timeBefore = systemTime();
118     for (uint32_t keyVal = 0; keyVal <= keyMask; keyVal++) {
119         Key shaderKey;
120         shaderKey.set(keyMask, keyVal);
121         uint32_t tex = shaderKey.getTextureTarget();
122         if (tex != Key::TEXTURE_OFF && tex != Key::TEXTURE_EXT && tex != Key::TEXTURE_2D) {
123             continue;
124         }
125         if (cache.count(shaderKey) == 0) {
126             cache.emplace(shaderKey, generateProgram(shaderKey));
127             shaderCount++;
128         }
129     }
130 
131     // Prime for sRGB->P3 conversion
132     if (useColorManagement) {
133         Key shaderKey;
134         shaderKey.set(Key::BLEND_MASK | Key::OUTPUT_TRANSFORM_MATRIX_MASK | Key::INPUT_TF_MASK |
135                               Key::OUTPUT_TF_MASK,
136                       Key::BLEND_PREMULT | Key::OUTPUT_TRANSFORM_MATRIX_ON | Key::INPUT_TF_SRGB |
137                               Key::OUTPUT_TF_SRGB);
138         for (int i = 0; i < 16; i++) {
139             shaderKey.set(Key::OPACITY_MASK,
140                           (i & 1) ? Key::OPACITY_OPAQUE : Key::OPACITY_TRANSLUCENT);
141             shaderKey.set(Key::ALPHA_MASK, (i & 2) ? Key::ALPHA_LT_ONE : Key::ALPHA_EQ_ONE);
142 
143             // Cache rounded corners
144             shaderKey.set(Key::ROUNDED_CORNERS_MASK,
145                           (i & 4) ? Key::ROUNDED_CORNERS_ON : Key::ROUNDED_CORNERS_OFF);
146 
147             // Cache texture off option for window transition
148             shaderKey.set(Key::TEXTURE_MASK, (i & 8) ? Key::TEXTURE_EXT : Key::TEXTURE_OFF);
149             if (cache.count(shaderKey) == 0) {
150                 cache.emplace(shaderKey, generateProgram(shaderKey));
151                 shaderCount++;
152             }
153         }
154     }
155 
156     nsecs_t timeAfter = systemTime();
157     float compileTimeMs = static_cast<float>(timeAfter - timeBefore) / 1.0E6;
158     ALOGD("shader cache generated - %u shaders in %f ms\n", shaderCount, compileTimeMs);
159 }
160 
computeKey(const Description & description)161 ProgramCache::Key ProgramCache::computeKey(const Description& description) {
162     Key needs;
163     needs.set(Key::TEXTURE_MASK,
164               !description.textureEnabled
165                       ? Key::TEXTURE_OFF
166                       : description.texture.getTextureTarget() == GL_TEXTURE_EXTERNAL_OES
167                               ? Key::TEXTURE_EXT
168                               : description.texture.getTextureTarget() == GL_TEXTURE_2D
169                                       ? Key::TEXTURE_2D
170                                       : Key::TEXTURE_OFF)
171             .set(Key::ALPHA_MASK, (description.color.a < 1) ? Key::ALPHA_LT_ONE : Key::ALPHA_EQ_ONE)
172             .set(Key::BLEND_MASK,
173                  description.isPremultipliedAlpha ? Key::BLEND_PREMULT : Key::BLEND_NORMAL)
174             .set(Key::OPACITY_MASK,
175                  description.isOpaque ? Key::OPACITY_OPAQUE : Key::OPACITY_TRANSLUCENT)
176             .set(Key::Key::INPUT_TRANSFORM_MATRIX_MASK,
177                  description.hasInputTransformMatrix() ? Key::INPUT_TRANSFORM_MATRIX_ON
178                                                        : Key::INPUT_TRANSFORM_MATRIX_OFF)
179             .set(Key::Key::OUTPUT_TRANSFORM_MATRIX_MASK,
180                  description.hasOutputTransformMatrix() || description.hasColorMatrix()
181                          ? Key::OUTPUT_TRANSFORM_MATRIX_ON
182                          : Key::OUTPUT_TRANSFORM_MATRIX_OFF)
183             .set(Key::ROUNDED_CORNERS_MASK,
184                  description.cornerRadius > 0 ? Key::ROUNDED_CORNERS_ON : Key::ROUNDED_CORNERS_OFF)
185             .set(Key::SHADOW_MASK, description.drawShadows ? Key::SHADOW_ON : Key::SHADOW_OFF);
186     needs.set(Key::Y410_BT2020_MASK,
187               description.isY410BT2020 ? Key::Y410_BT2020_ON : Key::Y410_BT2020_OFF);
188 
189     if (needs.hasTransformMatrix() ||
190         (description.inputTransferFunction != description.outputTransferFunction)) {
191         switch (description.inputTransferFunction) {
192             case Description::TransferFunction::LINEAR:
193             default:
194                 needs.set(Key::INPUT_TF_MASK, Key::INPUT_TF_LINEAR);
195                 break;
196             case Description::TransferFunction::SRGB:
197                 needs.set(Key::INPUT_TF_MASK, Key::INPUT_TF_SRGB);
198                 break;
199             case Description::TransferFunction::ST2084:
200                 needs.set(Key::INPUT_TF_MASK, Key::INPUT_TF_ST2084);
201                 break;
202             case Description::TransferFunction::HLG:
203                 needs.set(Key::INPUT_TF_MASK, Key::INPUT_TF_HLG);
204                 break;
205         }
206 
207         switch (description.outputTransferFunction) {
208             case Description::TransferFunction::LINEAR:
209             default:
210                 needs.set(Key::OUTPUT_TF_MASK, Key::OUTPUT_TF_LINEAR);
211                 break;
212             case Description::TransferFunction::SRGB:
213                 needs.set(Key::OUTPUT_TF_MASK, Key::OUTPUT_TF_SRGB);
214                 break;
215             case Description::TransferFunction::ST2084:
216                 needs.set(Key::OUTPUT_TF_MASK, Key::OUTPUT_TF_ST2084);
217                 break;
218             case Description::TransferFunction::HLG:
219                 needs.set(Key::OUTPUT_TF_MASK, Key::OUTPUT_TF_HLG);
220                 break;
221         }
222     }
223 
224     return needs;
225 }
226 
227 // Generate EOTF that converts signal values to relative display light,
228 // both normalized to [0, 1].
generateEOTF(Formatter & fs,const Key & needs)229 void ProgramCache::generateEOTF(Formatter& fs, const Key& needs) {
230     switch (needs.getInputTF()) {
231         case Key::INPUT_TF_SRGB:
232             fs << R"__SHADER__(
233                 float EOTF_sRGB(float srgb) {
234                     return srgb <= 0.04045 ? srgb / 12.92 : pow((srgb + 0.055) / 1.055, 2.4);
235                 }
236 
237                 vec3 EOTF_sRGB(const vec3 srgb) {
238                     return vec3(EOTF_sRGB(srgb.r), EOTF_sRGB(srgb.g), EOTF_sRGB(srgb.b));
239                 }
240 
241                 vec3 EOTF(const vec3 srgb) {
242                     return sign(srgb.rgb) * EOTF_sRGB(abs(srgb.rgb));
243                 }
244             )__SHADER__";
245             break;
246         case Key::INPUT_TF_ST2084:
247             fs << R"__SHADER__(
248                 vec3 EOTF(const highp vec3 color) {
249                     const highp float m1 = (2610.0 / 4096.0) / 4.0;
250                     const highp float m2 = (2523.0 / 4096.0) * 128.0;
251                     const highp float c1 = (3424.0 / 4096.0);
252                     const highp float c2 = (2413.0 / 4096.0) * 32.0;
253                     const highp float c3 = (2392.0 / 4096.0) * 32.0;
254 
255                     highp vec3 tmp = pow(clamp(color, 0.0, 1.0), 1.0 / vec3(m2));
256                     tmp = max(tmp - c1, 0.0) / (c2 - c3 * tmp);
257                     return pow(tmp, 1.0 / vec3(m1));
258                 }
259             )__SHADER__";
260             break;
261         case Key::INPUT_TF_HLG:
262             fs << R"__SHADER__(
263                 highp float EOTF_channel(const highp float channel) {
264                     const highp float a = 0.17883277;
265                     const highp float b = 0.28466892;
266                     const highp float c = 0.55991073;
267                     return channel <= 0.5 ? channel * channel / 3.0 :
268                             (exp((channel - c) / a) + b) / 12.0;
269                 }
270 
271                 vec3 EOTF(const highp vec3 color) {
272                     return vec3(EOTF_channel(color.r), EOTF_channel(color.g),
273                             EOTF_channel(color.b));
274                 }
275             )__SHADER__";
276             break;
277         default:
278             fs << R"__SHADER__(
279                 vec3 EOTF(const vec3 linear) {
280                     return linear;
281                 }
282             )__SHADER__";
283             break;
284     }
285 }
286 
generateToneMappingProcess(Formatter & fs,const Key & needs)287 void ProgramCache::generateToneMappingProcess(Formatter& fs, const Key& needs) {
288     // Convert relative light to absolute light.
289     switch (needs.getInputTF()) {
290         case Key::INPUT_TF_ST2084:
291             fs << R"__SHADER__(
292                 highp vec3 ScaleLuminance(highp vec3 color) {
293                     return color * 10000.0;
294                 }
295             )__SHADER__";
296             break;
297         case Key::INPUT_TF_HLG:
298             fs << R"__SHADER__(
299                 highp vec3 ScaleLuminance(highp vec3 color) {
300                     // The formula is:
301                     // alpha * pow(Y, gamma - 1.0) * color + beta;
302                     // where alpha is 1000.0, gamma is 1.2, beta is 0.0.
303                     return color * 1000.0 * pow(color.y, 0.2);
304                 }
305             )__SHADER__";
306             break;
307         default:
308             fs << R"__SHADER__(
309                 highp vec3 ScaleLuminance(highp vec3 color) {
310                     return color * displayMaxLuminance;
311                 }
312             )__SHADER__";
313             break;
314     }
315 
316     // Tone map absolute light to display luminance range.
317     switch (needs.getInputTF()) {
318         case Key::INPUT_TF_ST2084:
319         case Key::INPUT_TF_HLG:
320             switch (needs.getOutputTF()) {
321                 case Key::OUTPUT_TF_HLG:
322                     // Right now when mixed PQ and HLG contents are presented,
323                     // HLG content will always be converted to PQ. However, for
324                     // completeness, we simply clamp the value to [0.0, 1000.0].
325                     fs << R"__SHADER__(
326                         highp vec3 ToneMap(highp vec3 color) {
327                             return clamp(color, 0.0, 1000.0);
328                         }
329                     )__SHADER__";
330                     break;
331                 case Key::OUTPUT_TF_ST2084:
332                     fs << R"__SHADER__(
333                         highp vec3 ToneMap(highp vec3 color) {
334                             return color;
335                         }
336                     )__SHADER__";
337                     break;
338                 default:
339                     fs << R"__SHADER__(
340                         highp vec3 ToneMap(highp vec3 color) {
341                             float maxMasteringLumi = maxMasteringLuminance;
342                             float maxContentLumi = maxContentLuminance;
343                             float maxInLumi = min(maxMasteringLumi, maxContentLumi);
344                             float maxOutLumi = displayMaxLuminance;
345 
346                             float nits = color.y;
347 
348                             // clamp to max input luminance
349                             nits = clamp(nits, 0.0, maxInLumi);
350 
351                             // scale [0.0, maxInLumi] to [0.0, maxOutLumi]
352                             if (maxInLumi <= maxOutLumi) {
353                                 return color * (maxOutLumi / maxInLumi);
354                             } else {
355                                 // three control points
356                                 const float x0 = 10.0;
357                                 const float y0 = 17.0;
358                                 float x1 = maxOutLumi * 0.75;
359                                 float y1 = x1;
360                                 float x2 = x1 + (maxInLumi - x1) / 2.0;
361                                 float y2 = y1 + (maxOutLumi - y1) * 0.75;
362 
363                                 // horizontal distances between the last three control points
364                                 float h12 = x2 - x1;
365                                 float h23 = maxInLumi - x2;
366                                 // tangents at the last three control points
367                                 float m1 = (y2 - y1) / h12;
368                                 float m3 = (maxOutLumi - y2) / h23;
369                                 float m2 = (m1 + m3) / 2.0;
370 
371                                 if (nits < x0) {
372                                     // scale [0.0, x0] to [0.0, y0] linearly
373                                     float slope = y0 / x0;
374                                     return color * slope;
375                                 } else if (nits < x1) {
376                                     // scale [x0, x1] to [y0, y1] linearly
377                                     float slope = (y1 - y0) / (x1 - x0);
378                                     nits = y0 + (nits - x0) * slope;
379                                 } else if (nits < x2) {
380                                     // scale [x1, x2] to [y1, y2] using Hermite interp
381                                     float t = (nits - x1) / h12;
382                                     nits = (y1 * (1.0 + 2.0 * t) + h12 * m1 * t) * (1.0 - t) * (1.0 - t) +
383                                             (y2 * (3.0 - 2.0 * t) + h12 * m2 * (t - 1.0)) * t * t;
384                                 } else {
385                                     // scale [x2, maxInLumi] to [y2, maxOutLumi] using Hermite interp
386                                     float t = (nits - x2) / h23;
387                                     nits = (y2 * (1.0 + 2.0 * t) + h23 * m2 * t) * (1.0 - t) * (1.0 - t) +
388                                             (maxOutLumi * (3.0 - 2.0 * t) + h23 * m3 * (t - 1.0)) * t * t;
389                                 }
390                             }
391 
392                             // color.y is greater than x0 and is thus non-zero
393                             return color * (nits / color.y);
394                         }
395                     )__SHADER__";
396                     break;
397             }
398             break;
399         default:
400             // inverse tone map; the output luminance can be up to maxOutLumi.
401             fs << R"__SHADER__(
402                 highp vec3 ToneMap(highp vec3 color) {
403                     const float maxOutLumi = 3000.0;
404 
405                     const float x0 = 5.0;
406                     const float y0 = 2.5;
407                     float x1 = displayMaxLuminance * 0.7;
408                     float y1 = maxOutLumi * 0.15;
409                     float x2 = displayMaxLuminance * 0.9;
410                     float y2 = maxOutLumi * 0.45;
411                     float x3 = displayMaxLuminance;
412                     float y3 = maxOutLumi;
413 
414                     float c1 = y1 / 3.0;
415                     float c2 = y2 / 2.0;
416                     float c3 = y3 / 1.5;
417 
418                     float nits = color.y;
419 
420                     float scale;
421                     if (nits <= x0) {
422                         // scale [0.0, x0] to [0.0, y0] linearly
423                         const float slope = y0 / x0;
424                         return color * slope;
425                     } else if (nits <= x1) {
426                         // scale [x0, x1] to [y0, y1] using a curve
427                         float t = (nits - x0) / (x1 - x0);
428                         nits = (1.0 - t) * (1.0 - t) * y0 + 2.0 * (1.0 - t) * t * c1 + t * t * y1;
429                     } else if (nits <= x2) {
430                         // scale [x1, x2] to [y1, y2] using a curve
431                         float t = (nits - x1) / (x2 - x1);
432                         nits = (1.0 - t) * (1.0 - t) * y1 + 2.0 * (1.0 - t) * t * c2 + t * t * y2;
433                     } else {
434                         // scale [x2, x3] to [y2, y3] using a curve
435                         float t = (nits - x2) / (x3 - x2);
436                         nits = (1.0 - t) * (1.0 - t) * y2 + 2.0 * (1.0 - t) * t * c3 + t * t * y3;
437                     }
438 
439                     // color.y is greater than x0 and is thus non-zero
440                     return color * (nits / color.y);
441                 }
442             )__SHADER__";
443             break;
444     }
445 
446     // convert absolute light to relative light.
447     switch (needs.getOutputTF()) {
448         case Key::OUTPUT_TF_ST2084:
449             fs << R"__SHADER__(
450                 highp vec3 NormalizeLuminance(highp vec3 color) {
451                     return color / 10000.0;
452                 }
453             )__SHADER__";
454             break;
455         case Key::OUTPUT_TF_HLG:
456             fs << R"__SHADER__(
457                 highp vec3 NormalizeLuminance(highp vec3 color) {
458                     return color / 1000.0 * pow(color.y / 1000.0, -0.2 / 1.2);
459                 }
460             )__SHADER__";
461             break;
462         default:
463             fs << R"__SHADER__(
464                 highp vec3 NormalizeLuminance(highp vec3 color) {
465                     return color / displayMaxLuminance;
466                 }
467             )__SHADER__";
468             break;
469     }
470 }
471 
472 // Generate OOTF that modifies the relative scence light to relative display light.
generateOOTF(Formatter & fs,const ProgramCache::Key & needs)473 void ProgramCache::generateOOTF(Formatter& fs, const ProgramCache::Key& needs) {
474     if (!needs.needsToneMapping()) {
475         fs << R"__SHADER__(
476             highp vec3 OOTF(const highp vec3 color) {
477                 return color;
478             }
479         )__SHADER__";
480     } else {
481         generateToneMappingProcess(fs, needs);
482         fs << R"__SHADER__(
483             highp vec3 OOTF(const highp vec3 color) {
484                 return NormalizeLuminance(ToneMap(ScaleLuminance(color)));
485             }
486         )__SHADER__";
487     }
488 }
489 
490 // Generate OETF that converts relative display light to signal values,
491 // both normalized to [0, 1]
generateOETF(Formatter & fs,const Key & needs)492 void ProgramCache::generateOETF(Formatter& fs, const Key& needs) {
493     switch (needs.getOutputTF()) {
494         case Key::OUTPUT_TF_SRGB:
495             fs << R"__SHADER__(
496                 float OETF_sRGB(const float linear) {
497                     return linear <= 0.0031308 ?
498                             linear * 12.92 : (pow(linear, 1.0 / 2.4) * 1.055) - 0.055;
499                 }
500 
501                 vec3 OETF_sRGB(const vec3 linear) {
502                     return vec3(OETF_sRGB(linear.r), OETF_sRGB(linear.g), OETF_sRGB(linear.b));
503                 }
504 
505                 vec3 OETF(const vec3 linear) {
506                     return sign(linear.rgb) * OETF_sRGB(abs(linear.rgb));
507                 }
508             )__SHADER__";
509             break;
510         case Key::OUTPUT_TF_ST2084:
511             fs << R"__SHADER__(
512                 vec3 OETF(const vec3 linear) {
513                     const highp float m1 = (2610.0 / 4096.0) / 4.0;
514                     const highp float m2 = (2523.0 / 4096.0) * 128.0;
515                     const highp float c1 = (3424.0 / 4096.0);
516                     const highp float c2 = (2413.0 / 4096.0) * 32.0;
517                     const highp float c3 = (2392.0 / 4096.0) * 32.0;
518 
519                     highp vec3 tmp = pow(linear, vec3(m1));
520                     tmp = (c1 + c2 * tmp) / (1.0 + c3 * tmp);
521                     return pow(tmp, vec3(m2));
522                 }
523             )__SHADER__";
524             break;
525         case Key::OUTPUT_TF_HLG:
526             fs << R"__SHADER__(
527                 highp float OETF_channel(const highp float channel) {
528                     const highp float a = 0.17883277;
529                     const highp float b = 0.28466892;
530                     const highp float c = 0.55991073;
531                     return channel <= 1.0 / 12.0 ? sqrt(3.0 * channel) :
532                             a * log(12.0 * channel - b) + c;
533                 }
534 
535                 vec3 OETF(const highp vec3 color) {
536                     return vec3(OETF_channel(color.r), OETF_channel(color.g),
537                             OETF_channel(color.b));
538                 }
539             )__SHADER__";
540             break;
541         default:
542             fs << R"__SHADER__(
543                 vec3 OETF(const vec3 linear) {
544                     return linear;
545                 }
546             )__SHADER__";
547             break;
548     }
549 }
550 
generateVertexShader(const Key & needs)551 String8 ProgramCache::generateVertexShader(const Key& needs) {
552     Formatter vs;
553     if (needs.hasTextureCoords()) {
554         vs << "attribute vec4 texCoords;"
555            << "varying vec2 outTexCoords;";
556     }
557     if (needs.hasRoundedCorners()) {
558         vs << "attribute lowp vec4 cropCoords;";
559         vs << "varying lowp vec2 outCropCoords;";
560     }
561     if (needs.drawShadows()) {
562         vs << "attribute lowp vec4 shadowColor;";
563         vs << "varying lowp vec4 outShadowColor;";
564         vs << "attribute lowp vec4 shadowParams;";
565         vs << "varying lowp vec3 outShadowParams;";
566     }
567     vs << "attribute vec4 position;"
568        << "uniform mat4 projection;"
569        << "uniform mat4 texture;"
570        << "void main(void) {" << indent << "gl_Position = projection * position;";
571     if (needs.hasTextureCoords()) {
572         vs << "outTexCoords = (texture * texCoords).st;";
573     }
574     if (needs.hasRoundedCorners()) {
575         vs << "outCropCoords = cropCoords.st;";
576     }
577     if (needs.drawShadows()) {
578         vs << "outShadowColor = shadowColor;";
579         vs << "outShadowParams = shadowParams.xyz;";
580     }
581     vs << dedent << "}";
582     return vs.getString();
583 }
584 
generateFragmentShader(const Key & needs)585 String8 ProgramCache::generateFragmentShader(const Key& needs) {
586     Formatter fs;
587     if (needs.getTextureTarget() == Key::TEXTURE_EXT) {
588         fs << "#extension GL_OES_EGL_image_external : require";
589     }
590 
591     // default precision is required-ish in fragment shaders
592     fs << "precision mediump float;";
593 
594     if (needs.getTextureTarget() == Key::TEXTURE_EXT) {
595         fs << "uniform samplerExternalOES sampler;";
596     } else if (needs.getTextureTarget() == Key::TEXTURE_2D) {
597         fs << "uniform sampler2D sampler;";
598     }
599 
600     if (needs.hasTextureCoords()) {
601         fs << "varying vec2 outTexCoords;";
602     }
603 
604     if (needs.hasRoundedCorners()) {
605         // Rounded corners implementation using a signed distance function.
606         fs << R"__SHADER__(
607             uniform float cornerRadius;
608             uniform vec2 cropCenter;
609             varying vec2 outCropCoords;
610 
611             /**
612              * This function takes the current crop coordinates and calculates an alpha value based
613              * on the corner radius and distance from the crop center.
614              */
615             float applyCornerRadius(vec2 cropCoords)
616             {
617                 vec2 position = cropCoords - cropCenter;
618                 // Scale down the dist vector here, as otherwise large corner
619                 // radii can cause floating point issues when computing the norm
620                 vec2 dist = (abs(position) - cropCenter + vec2(cornerRadius)) / 16.0;
621                 // Once we've found the norm, then scale back up.
622                 float plane = length(max(dist, vec2(0.0))) * 16.0;
623                 return 1.0 - clamp(plane - cornerRadius, 0.0, 1.0);
624             }
625             )__SHADER__";
626     }
627 
628     if (needs.drawShadows()) {
629         fs << R"__SHADER__(
630             varying lowp vec4 outShadowColor;
631             varying lowp vec3 outShadowParams;
632 
633             /**
634              * Returns the shadow color.
635              */
636             vec4 getShadowColor()
637             {
638                 lowp float d = length(outShadowParams.xy);
639                 vec2 uv = vec2(outShadowParams.z * (1.0 - d), 0.5);
640                 lowp float factor = texture2D(sampler, uv).a;
641                 return outShadowColor * factor;
642             }
643             )__SHADER__";
644     }
645 
646     if (needs.getTextureTarget() == Key::TEXTURE_OFF || needs.hasAlpha()) {
647         fs << "uniform vec4 color;";
648     }
649 
650     if (needs.isY410BT2020()) {
651         fs << R"__SHADER__(
652             vec3 convertY410BT2020(const vec3 color) {
653                 const vec3 offset = vec3(0.0625, 0.5, 0.5);
654                 const mat3 transform = mat3(
655                     vec3(1.1678,  1.1678, 1.1678),
656                     vec3(   0.0, -0.1878, 2.1481),
657                     vec3(1.6836, -0.6523,   0.0));
658                 // Y is in G, U is in R, and V is in B
659                 return clamp(transform * (color.grb - offset), 0.0, 1.0);
660             }
661             )__SHADER__";
662     }
663 
664     if (needs.hasTransformMatrix() || (needs.getInputTF() != needs.getOutputTF())) {
665         if (needs.needsToneMapping()) {
666             fs << "uniform float displayMaxLuminance;";
667             fs << "uniform float maxMasteringLuminance;";
668             fs << "uniform float maxContentLuminance;";
669         }
670 
671         if (needs.hasInputTransformMatrix()) {
672             fs << "uniform mat4 inputTransformMatrix;";
673             fs << R"__SHADER__(
674                 highp vec3 InputTransform(const highp vec3 color) {
675                     return clamp(vec3(inputTransformMatrix * vec4(color, 1.0)), 0.0, 1.0);
676                 }
677             )__SHADER__";
678         } else {
679             fs << R"__SHADER__(
680                 highp vec3 InputTransform(const highp vec3 color) {
681                     return color;
682                 }
683             )__SHADER__";
684         }
685 
686         // the transformation from a wider colorspace to a narrower one can
687         // result in >1.0 or <0.0 pixel values
688         if (needs.hasOutputTransformMatrix()) {
689             fs << "uniform mat4 outputTransformMatrix;";
690             fs << R"__SHADER__(
691                 highp vec3 OutputTransform(const highp vec3 color) {
692                     return clamp(vec3(outputTransformMatrix * vec4(color, 1.0)), 0.0, 1.0);
693                 }
694             )__SHADER__";
695         } else {
696             fs << R"__SHADER__(
697                 highp vec3 OutputTransform(const highp vec3 color) {
698                     return clamp(color, 0.0, 1.0);
699                 }
700             )__SHADER__";
701         }
702 
703         generateEOTF(fs, needs);
704         generateOOTF(fs, needs);
705         generateOETF(fs, needs);
706     }
707 
708     fs << "void main(void) {" << indent;
709     if (needs.drawShadows()) {
710         fs << "gl_FragColor = getShadowColor();";
711     } else {
712         if (needs.isTexturing()) {
713             fs << "gl_FragColor = texture2D(sampler, outTexCoords);";
714             if (needs.isY410BT2020()) {
715                 fs << "gl_FragColor.rgb = convertY410BT2020(gl_FragColor.rgb);";
716             }
717         } else {
718             fs << "gl_FragColor.rgb = color.rgb;";
719             fs << "gl_FragColor.a = 1.0;";
720         }
721         if (needs.isOpaque()) {
722             fs << "gl_FragColor.a = 1.0;";
723         }
724         if (needs.hasAlpha()) {
725             // modulate the current alpha value with alpha set
726             if (needs.isPremultiplied()) {
727                 // ... and the color too if we're premultiplied
728                 fs << "gl_FragColor *= color.a;";
729             } else {
730                 fs << "gl_FragColor.a *= color.a;";
731             }
732         }
733     }
734 
735     if (needs.hasTransformMatrix() || (needs.getInputTF() != needs.getOutputTF())) {
736         if (!needs.isOpaque() && needs.isPremultiplied()) {
737             // un-premultiply if needed before linearization
738             // avoid divide by 0 by adding 0.5/256 to the alpha channel
739             fs << "gl_FragColor.rgb = gl_FragColor.rgb / (gl_FragColor.a + 0.0019);";
740         }
741         fs << "gl_FragColor.rgb = "
742               "OETF(OutputTransform(OOTF(InputTransform(EOTF(gl_FragColor.rgb)))));";
743         if (!needs.isOpaque() && needs.isPremultiplied()) {
744             // and re-premultiply if needed after gamma correction
745             fs << "gl_FragColor.rgb = gl_FragColor.rgb * (gl_FragColor.a + 0.0019);";
746         }
747     }
748 
749     if (needs.hasRoundedCorners()) {
750         if (needs.isPremultiplied()) {
751             fs << "gl_FragColor *= vec4(applyCornerRadius(outCropCoords));";
752         } else {
753             fs << "gl_FragColor.a *= applyCornerRadius(outCropCoords);";
754         }
755     }
756 
757     fs << dedent << "}";
758     return fs.getString();
759 }
760 
generateProgram(const Key & needs)761 std::unique_ptr<Program> ProgramCache::generateProgram(const Key& needs) {
762     ATRACE_CALL();
763 
764     // vertex shader
765     String8 vs = generateVertexShader(needs);
766 
767     // fragment shader
768     String8 fs = generateFragmentShader(needs);
769 
770     return std::make_unique<Program>(needs, vs.string(), fs.string());
771 }
772 
useProgram(EGLContext context,const Description & description)773 void ProgramCache::useProgram(EGLContext context, const Description& description) {
774     // generate the key for the shader based on the description
775     Key needs(computeKey(description));
776 
777     // look-up the program in the cache
778     auto& cache = mCaches[context];
779     auto it = cache.find(needs);
780     if (it == cache.end()) {
781         // we didn't find our program, so generate one...
782         nsecs_t time = systemTime();
783         it = cache.emplace(needs, generateProgram(needs)).first;
784         time = systemTime() - time;
785 
786         ALOGV(">>> generated new program for context %p: needs=%08X, time=%u ms (%zu programs)",
787               context, needs.mKey, uint32_t(ns2ms(time)), cache.size());
788     }
789 
790     // here we have a suitable program for this description
791     std::unique_ptr<Program>& program = it->second;
792     if (program->isValid()) {
793         program->use();
794         program->setUniforms(description);
795     }
796 }
797 
798 } // namespace gl
799 } // namespace renderengine
800 } // namespace android
801