Move compute shader functions from the header to the footer; easier to unify with...
[movit] / effect_chain.cpp
1 #include <epoxy/gl.h>
2 #include <assert.h>
3 #include <math.h>
4 #include <stddef.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <algorithm>
9 #include <set>
10 #include <stack>
11 #include <utility>
12 #include <vector>
13 #include <Eigen/Core>
14
15 #include "alpha_division_effect.h"
16 #include "alpha_multiplication_effect.h"
17 #include "colorspace_conversion_effect.h"
18 #include "dither_effect.h"
19 #include "effect.h"
20 #include "effect_chain.h"
21 #include "effect_util.h"
22 #include "gamma_compression_effect.h"
23 #include "gamma_expansion_effect.h"
24 #include "init.h"
25 #include "input.h"
26 #include "resource_pool.h"
27 #include "util.h"
28 #include "ycbcr_conversion_effect.h"
29
30 using namespace Eigen;
31 using namespace std;
32
33 namespace movit {
34
35 namespace {
36
37 // An effect that does nothing.
38 class IdentityEffect : public Effect {
39 public:
40         IdentityEffect() {}
41         virtual string effect_type_id() const { return "IdentityEffect"; }
42         string output_fragment_shader() { return read_file("identity.frag"); }
43 };
44
45 }  // namespace
46
47 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
48         : aspect_nom(aspect_nom),
49           aspect_denom(aspect_denom),
50           output_color_rgba(false),
51           num_output_color_ycbcr(0),
52           dither_effect(nullptr),
53           ycbcr_conversion_effect_node(nullptr),
54           intermediate_format(GL_RGBA16F),
55           intermediate_transformation(NO_FRAMEBUFFER_TRANSFORMATION),
56           num_dither_bits(0),
57           output_origin(OUTPUT_ORIGIN_BOTTOM_LEFT),
58           finalized(false),
59           resource_pool(resource_pool),
60           do_phase_timing(false) {
61         if (resource_pool == nullptr) {
62                 this->resource_pool = new ResourcePool();
63                 owns_resource_pool = true;
64         } else {
65                 owns_resource_pool = false;
66         }
67
68         // Generate a VBO with some data in (shared position and texture coordinate data).
69         float vertices[] = {
70                 0.0f, 2.0f,
71                 0.0f, 0.0f,
72                 2.0f, 0.0f
73         };
74         vbo = generate_vbo(2, GL_FLOAT, sizeof(vertices), vertices);
75 }
76
77 EffectChain::~EffectChain()
78 {
79         for (unsigned i = 0; i < nodes.size(); ++i) {
80                 delete nodes[i]->effect;
81                 delete nodes[i];
82         }
83         for (unsigned i = 0; i < phases.size(); ++i) {
84                 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
85                 delete phases[i];
86         }
87         if (owns_resource_pool) {
88                 delete resource_pool;
89         }
90         glDeleteBuffers(1, &vbo);
91         check_error();
92 }
93
94 Input *EffectChain::add_input(Input *input)
95 {
96         assert(!finalized);
97         inputs.push_back(input);
98         add_node(input);
99         return input;
100 }
101
102 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
103 {
104         assert(!finalized);
105         assert(!output_color_rgba);
106         output_format = format;
107         output_alpha_format = alpha_format;
108         output_color_rgba = true;
109 }
110
111 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
112                                    const YCbCrFormat &ycbcr_format, YCbCrOutputSplitting output_splitting,
113                                    GLenum output_type)
114 {
115         assert(!finalized);
116         assert(num_output_color_ycbcr < 2);
117         output_format = format;
118         output_alpha_format = alpha_format;
119
120         if (num_output_color_ycbcr == 1) {
121                 // Check that the format is the same.
122                 assert(output_ycbcr_format.luma_coefficients == ycbcr_format.luma_coefficients);
123                 assert(output_ycbcr_format.full_range == ycbcr_format.full_range);
124                 assert(output_ycbcr_format.num_levels == ycbcr_format.num_levels);
125                 assert(output_ycbcr_format.chroma_subsampling_x == 1);
126                 assert(output_ycbcr_format.chroma_subsampling_y == 1);
127                 assert(output_ycbcr_type == output_type);
128         } else {
129                 output_ycbcr_format = ycbcr_format;
130                 output_ycbcr_type = output_type;
131         }
132         output_ycbcr_splitting[num_output_color_ycbcr++] = output_splitting;
133
134         assert(ycbcr_format.chroma_subsampling_x == 1);
135         assert(ycbcr_format.chroma_subsampling_y == 1);
136 }
137
138 void EffectChain::change_ycbcr_output_format(const YCbCrFormat &ycbcr_format)
139 {
140         assert(num_output_color_ycbcr > 0);
141         assert(output_ycbcr_format.chroma_subsampling_x == 1);
142         assert(output_ycbcr_format.chroma_subsampling_y == 1);
143
144         output_ycbcr_format = ycbcr_format;
145         if (finalized) {
146                 YCbCrConversionEffect *effect = (YCbCrConversionEffect *)(ycbcr_conversion_effect_node->effect);
147                 effect->change_output_format(ycbcr_format);
148         }
149 }
150
151 Node *EffectChain::add_node(Effect *effect)
152 {
153         for (unsigned i = 0; i < nodes.size(); ++i) {
154                 assert(nodes[i]->effect != effect);
155         }
156
157         Node *node = new Node;
158         node->effect = effect;
159         node->disabled = false;
160         node->output_color_space = COLORSPACE_INVALID;
161         node->output_gamma_curve = GAMMA_INVALID;
162         node->output_alpha_type = ALPHA_INVALID;
163         node->needs_mipmaps = false;
164         node->one_to_one_sampling = false;
165
166         nodes.push_back(node);
167         node_map[effect] = node;
168         effect->inform_added(this);
169         return node;
170 }
171
172 void EffectChain::connect_nodes(Node *sender, Node *receiver)
173 {
174         sender->outgoing_links.push_back(receiver);
175         receiver->incoming_links.push_back(sender);
176 }
177
178 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
179 {
180         new_receiver->incoming_links = old_receiver->incoming_links;
181         old_receiver->incoming_links.clear();
182         
183         for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
184                 Node *sender = new_receiver->incoming_links[i];
185                 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
186                         if (sender->outgoing_links[j] == old_receiver) {
187                                 sender->outgoing_links[j] = new_receiver;
188                         }
189                 }
190         }       
191 }
192
193 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
194 {
195         new_sender->outgoing_links = old_sender->outgoing_links;
196         old_sender->outgoing_links.clear();
197         
198         for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
199                 Node *receiver = new_sender->outgoing_links[i];
200                 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
201                         if (receiver->incoming_links[j] == old_sender) {
202                                 receiver->incoming_links[j] = new_sender;
203                         }
204                 }
205         }       
206 }
207
208 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
209 {
210         for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
211                 if (sender->outgoing_links[i] == receiver) {
212                         sender->outgoing_links[i] = middle;
213                         middle->incoming_links.push_back(sender);
214                 }
215         }
216         for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
217                 if (receiver->incoming_links[i] == sender) {
218                         receiver->incoming_links[i] = middle;
219                         middle->outgoing_links.push_back(receiver);
220                 }
221         }
222
223         assert(middle->incoming_links.size() == middle->effect->num_inputs());
224 }
225
226 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
227 {
228         assert(node->effect->needs_texture_bounce());
229         assert(input_num < node->incoming_links.size());
230         assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
231         assert(node->incoming_links[input_num]->bound_sampler_num < 8);
232         return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
233 }
234
235 GLenum EffectChain::has_input_sampler(Node *node, unsigned input_num) const
236 {
237         assert(input_num < node->incoming_links.size());
238         return node->incoming_links[input_num]->bound_sampler_num >= 0 &&
239                 node->incoming_links[input_num]->bound_sampler_num < 8;
240 }
241
242 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
243 {
244         if (node->output_gamma_curve == GAMMA_LINEAR &&
245             node->effect->effect_type_id() != "GammaCompressionEffect") {
246                 return;
247         }
248         if (node->effect->num_inputs() == 0) {
249                 nonlinear_inputs->push_back(node);
250         } else {
251                 assert(node->effect->num_inputs() == node->incoming_links.size());
252                 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
253                         find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
254                 }
255         }
256 }
257
258 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
259 {
260         assert(!finalized);
261         assert(inputs.size() == effect->num_inputs());
262         Node *node = add_node(effect);
263         for (unsigned i = 0; i < inputs.size(); ++i) {
264                 assert(node_map.count(inputs[i]) != 0);
265                 connect_nodes(node_map[inputs[i]], node);
266         }
267         return effect;
268 }
269
270 // ESSL doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
271 string replace_prefix(const string &text, const string &prefix)
272 {
273         string output;
274         size_t start = 0;
275
276         while (start < text.size()) {
277                 size_t pos = text.find("PREFIX(", start);
278                 if (pos == string::npos) {
279                         output.append(text.substr(start, string::npos));
280                         break;
281                 }
282
283                 output.append(text.substr(start, pos - start));
284                 output.append(prefix);
285                 output.append("_");
286
287                 pos += strlen("PREFIX(");
288         
289                 // Output stuff until we find the matching ), which we then eat.
290                 int depth = 1;
291                 size_t end_arg_pos = pos;
292                 while (end_arg_pos < text.size()) {
293                         if (text[end_arg_pos] == '(') {
294                                 ++depth;
295                         } else if (text[end_arg_pos] == ')') {
296                                 --depth;
297                                 if (depth == 0) {
298                                         break;
299                                 }
300                         }
301                         ++end_arg_pos;
302                 }
303                 output.append(text.substr(pos, end_arg_pos - pos));
304                 ++end_arg_pos;
305                 assert(depth == 0);
306                 start = end_arg_pos;
307         }
308         return output;
309 }
310
311 namespace {
312
313 template<class T>
314 void extract_uniform_declarations(const vector<Uniform<T>> &effect_uniforms,
315                                   const string &type_specifier,
316                                   const string &effect_id,
317                                   vector<Uniform<T>> *phase_uniforms,
318                                   string *glsl_string)
319 {
320         for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
321                 phase_uniforms->push_back(effect_uniforms[i]);
322                 phase_uniforms->back().prefix = effect_id;
323
324                 *glsl_string += string("uniform ") + type_specifier + " " + effect_id
325                         + "_" + effect_uniforms[i].name + ";\n";
326         }
327 }
328
329 template<class T>
330 void extract_uniform_array_declarations(const vector<Uniform<T>> &effect_uniforms,
331                                         const string &type_specifier,
332                                         const string &effect_id,
333                                         vector<Uniform<T>> *phase_uniforms,
334                                         string *glsl_string)
335 {
336         for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
337                 phase_uniforms->push_back(effect_uniforms[i]);
338                 phase_uniforms->back().prefix = effect_id;
339
340                 char buf[256];
341                 snprintf(buf, sizeof(buf), "uniform %s %s_%s[%d];\n",
342                         type_specifier.c_str(), effect_id.c_str(),
343                         effect_uniforms[i].name.c_str(),
344                         int(effect_uniforms[i].num_values));
345                 *glsl_string += buf;
346         }
347 }
348
349 template<class T>
350 void collect_uniform_locations(GLuint glsl_program_num, vector<Uniform<T>> *phase_uniforms)
351 {
352         for (unsigned i = 0; i < phase_uniforms->size(); ++i) {
353                 Uniform<T> &uniform = (*phase_uniforms)[i];
354                 uniform.location = get_uniform_location(glsl_program_num, uniform.prefix, uniform.name);
355         }
356 }
357
358 }  // namespace
359
360 void EffectChain::compile_glsl_program(Phase *phase)
361 {
362         string frag_shader_header;
363         if (phase->is_compute_shader) {
364                 frag_shader_header = read_file("header.comp");
365         } else {
366                 frag_shader_header = read_version_dependent_file("header", "frag");
367         }
368         string frag_shader = "";
369
370         // Create functions and uniforms for all the texture inputs that we need.
371         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
372                 Node *input = phase->inputs[i]->output_node;
373                 char effect_id[256];
374                 sprintf(effect_id, "in%u", i);
375                 phase->effect_ids.insert(make_pair(input, effect_id));
376         
377                 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
378                 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
379                 frag_shader += "\tvec4 tmp = tex2D(tex_" + string(effect_id) + ", tc);\n";
380
381                 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
382                     phase->inputs[i]->output_node->output_gamma_curve == GAMMA_LINEAR) {
383                         frag_shader += "\ttmp.rgb *= tmp.rgb;\n";
384                 }
385
386                 frag_shader += "\treturn tmp;\n";
387                 frag_shader += "}\n";
388                 frag_shader += "\n";
389
390                 Uniform<int> uniform;
391                 uniform.name = effect_id;
392                 uniform.value = &phase->input_samplers[i];
393                 uniform.prefix = "tex";
394                 uniform.num_values = 1;
395                 uniform.location = -1;
396                 phase->uniforms_sampler2d.push_back(uniform);
397         }
398
399         // Give each effect in the phase its own ID.
400         for (unsigned i = 0; i < phase->effects.size(); ++i) {
401                 Node *node = phase->effects[i];
402                 char effect_id[256];
403                 sprintf(effect_id, "eff%u", i);
404                 phase->effect_ids.insert(make_pair(node, effect_id));
405         }
406
407         for (unsigned i = 0; i < phase->effects.size(); ++i) {
408                 Node *node = phase->effects[i];
409                 const string effect_id = phase->effect_ids[node];
410                 if (node->incoming_links.size() == 1) {
411                         frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
412                 } else {
413                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
414                                 char buf[256];
415                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
416                                 frag_shader += buf;
417                         }
418                 }
419         
420                 frag_shader += "\n";
421                 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
422                 if (node->effect->is_compute_shader()) {
423                         frag_shader += string("#define NORMALIZE_TEXTURE_COORDS(tc) ((tc) * ") + effect_id + "_inv_output_size + " + effect_id + "_output_texcoord_adjust)\n";
424                 }
425                 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
426                 frag_shader += "#undef FUNCNAME\n";
427                 if (node->incoming_links.size() == 1) {
428                         frag_shader += "#undef INPUT\n";
429                 } else {
430                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
431                                 char buf[256];
432                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
433                                 frag_shader += buf;
434                         }
435                 }
436                 frag_shader += "\n";
437         }
438         frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
439
440         // If we're the last phase, add the right #defines for Y'CbCr multi-output as needed.
441         vector<string> frag_shader_outputs;  // In order.
442         if (phase->output_node->outgoing_links.empty() && num_output_color_ycbcr > 0) {
443                 switch (output_ycbcr_splitting[0]) {
444                 case YCBCR_OUTPUT_INTERLEAVED:
445                         // No #defines set.
446                         frag_shader_outputs.push_back("FragColor");
447                         break;
448                 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
449                         frag_shader += "#define YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
450                         frag_shader_outputs.push_back("Y");
451                         frag_shader_outputs.push_back("Chroma");
452                         break;
453                 case YCBCR_OUTPUT_PLANAR:
454                         frag_shader += "#define YCBCR_OUTPUT_PLANAR 1\n";
455                         frag_shader_outputs.push_back("Y");
456                         frag_shader_outputs.push_back("Cb");
457                         frag_shader_outputs.push_back("Cr");
458                         break;
459                 default:
460                         assert(false);
461                 }
462
463                 if (num_output_color_ycbcr > 1) {
464                         switch (output_ycbcr_splitting[1]) {
465                         case YCBCR_OUTPUT_INTERLEAVED:
466                                 frag_shader += "#define SECOND_YCBCR_OUTPUT_INTERLEAVED 1\n";
467                                 frag_shader_outputs.push_back("YCbCr2");
468                                 break;
469                         case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
470                                 frag_shader += "#define SECOND_YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
471                                 frag_shader_outputs.push_back("Y2");
472                                 frag_shader_outputs.push_back("Chroma2");
473                                 break;
474                         case YCBCR_OUTPUT_PLANAR:
475                                 frag_shader += "#define SECOND_YCBCR_OUTPUT_PLANAR 1\n";
476                                 frag_shader_outputs.push_back("Y2");
477                                 frag_shader_outputs.push_back("Cb2");
478                                 frag_shader_outputs.push_back("Cr2");
479                                 break;
480                         default:
481                                 assert(false);
482                         }
483                 }
484
485                 if (output_color_rgba) {
486                         // Note: Needs to come in the header, because not only the
487                         // output needs to see it (YCbCrConversionEffect and DitherEffect
488                         // do, too).
489                         frag_shader_header += "#define YCBCR_ALSO_OUTPUT_RGBA 1\n";
490                         frag_shader_outputs.push_back("RGBA");
491                 }
492         }
493
494         // If we're bouncing to a temporary texture, signal transformation if desired.
495         if (!phase->output_node->outgoing_links.empty()) {
496                 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
497                     phase->output_node->output_gamma_curve == GAMMA_LINEAR) {
498                         frag_shader += "#define SQUARE_ROOT_TRANSFORMATION 1\n";
499                 }
500         }
501
502         if (phase->is_compute_shader) {
503                 frag_shader.append(read_file("footer.comp"));
504                 phase->output_node->effect->register_uniform_vec2("inv_output_size", (float *)&phase->inv_output_size);
505                 phase->output_node->effect->register_uniform_vec2("output_texcoord_adjust", (float *)&phase->output_texcoord_adjust);
506         } else {
507                 frag_shader.append(read_file("footer.frag"));
508         }
509
510         // Collect uniforms from all effects and output them. Note that this needs
511         // to happen after output_fragment_shader(), even though the uniforms come
512         // before in the output source, since output_fragment_shader() is allowed
513         // to register new uniforms (e.g. arrays that are of unknown length until
514         // finalization time).
515         // TODO: Make a uniform block for platforms that support it.
516         string frag_shader_uniforms = "";
517         for (unsigned i = 0; i < phase->effects.size(); ++i) {
518                 Node *node = phase->effects[i];
519                 Effect *effect = node->effect;
520                 const string effect_id = phase->effect_ids[node];
521                 extract_uniform_declarations(effect->uniforms_image2d, "image2D", effect_id, &phase->uniforms_image2d, &frag_shader_uniforms);
522                 extract_uniform_declarations(effect->uniforms_sampler2d, "sampler2D", effect_id, &phase->uniforms_sampler2d, &frag_shader_uniforms);
523                 extract_uniform_declarations(effect->uniforms_bool, "bool", effect_id, &phase->uniforms_bool, &frag_shader_uniforms);
524                 extract_uniform_declarations(effect->uniforms_int, "int", effect_id, &phase->uniforms_int, &frag_shader_uniforms);
525                 extract_uniform_declarations(effect->uniforms_float, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
526                 extract_uniform_declarations(effect->uniforms_vec2, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
527                 extract_uniform_declarations(effect->uniforms_vec3, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
528                 extract_uniform_declarations(effect->uniforms_vec4, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
529                 extract_uniform_array_declarations(effect->uniforms_float_array, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
530                 extract_uniform_array_declarations(effect->uniforms_vec2_array, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
531                 extract_uniform_array_declarations(effect->uniforms_vec3_array, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
532                 extract_uniform_array_declarations(effect->uniforms_vec4_array, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
533                 extract_uniform_declarations(effect->uniforms_mat3, "mat3", effect_id, &phase->uniforms_mat3, &frag_shader_uniforms);
534         }
535
536         frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
537
538         string vert_shader = read_version_dependent_file("vs", "vert");
539
540         // If we're the last phase and need to flip the picture to compensate for
541         // the origin, tell the vertex shader so.
542         if (phase->output_node->outgoing_links.empty() && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
543                 const string needle = "#define FLIP_ORIGIN 0";
544                 size_t pos = vert_shader.find(needle);
545                 assert(pos != string::npos);
546
547                 vert_shader[pos + needle.size() - 1] = '1';
548         }
549
550         if (phase->is_compute_shader) {
551                 phase->glsl_program_num = resource_pool->compile_glsl_compute_program(frag_shader);
552
553                 Uniform<int> uniform;
554                 uniform.name = "outbuf";
555                 uniform.value = &phase->outbuf_image_unit;
556                 uniform.prefix = "tex";
557                 uniform.num_values = 1;
558                 uniform.location = -1;
559                 phase->uniforms_image2d.push_back(uniform);
560         } else {
561                 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader, frag_shader_outputs);
562         }
563         GLint position_attribute_index = glGetAttribLocation(phase->glsl_program_num, "position");
564         GLint texcoord_attribute_index = glGetAttribLocation(phase->glsl_program_num, "texcoord");
565         if (position_attribute_index != -1) {
566                 phase->attribute_indexes.insert(position_attribute_index);
567         }
568         if (texcoord_attribute_index != -1) {
569                 phase->attribute_indexes.insert(texcoord_attribute_index);
570         }
571
572         // Collect the resulting location numbers for each uniform.
573         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_image2d);
574         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
575         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
576         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
577         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
578         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
579         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
580         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
581         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
582 }
583
584 // Construct GLSL programs, starting at the given effect and following
585 // the chain from there. We end a program every time we come to an effect
586 // marked as "needs texture bounce", one that is used by multiple other
587 // effects, every time we need to bounce due to output size change
588 // (not all size changes require ending), and of course at the end.
589 //
590 // We follow a quite simple depth-first search from the output, although
591 // without recursing explicitly within each phase.
592 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
593 {
594         if (completed_effects->count(output)) {
595                 return (*completed_effects)[output];
596         }
597
598         Phase *phase = new Phase;
599         phase->output_node = output;
600         phase->is_compute_shader = output->effect->is_compute_shader();
601
602         // If the output effect has one-to-one sampling, we try to trace this
603         // status down through the dependency chain. This is important in case
604         // we hit an effect that changes output size (and not sets a virtual
605         // output size); if we have one-to-one sampling, we don't have to break
606         // the phase.
607         output->one_to_one_sampling = output->effect->one_to_one_sampling();
608
609         // Effects that we have yet to calculate, but that we know should
610         // be in the current phase.
611         stack<Node *> effects_todo_this_phase;
612         effects_todo_this_phase.push(output);
613
614         while (!effects_todo_this_phase.empty()) {
615                 Node *node = effects_todo_this_phase.top();
616                 effects_todo_this_phase.pop();
617
618                 if (node->effect->needs_mipmaps()) {
619                         node->needs_mipmaps = true;
620                 }
621
622                 // This should currently only happen for effects that are inputs
623                 // (either true inputs or phase outputs). We special-case inputs,
624                 // and then deduplicate phase outputs below.
625                 if (node->effect->num_inputs() == 0) {
626                         if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
627                                 continue;
628                         }
629                 } else {
630                         assert(completed_effects->count(node) == 0);
631                 }
632
633                 phase->effects.push_back(node);
634
635                 // Find all the dependencies of this effect, and add them to the stack.
636                 vector<Node *> deps = node->incoming_links;
637                 assert(node->effect->num_inputs() == deps.size());
638                 for (unsigned i = 0; i < deps.size(); ++i) {
639                         bool start_new_phase = false;
640
641                         if (node->effect->needs_texture_bounce() &&
642                             !deps[i]->effect->is_single_texture() &&
643                             !deps[i]->effect->override_disable_bounce()) {
644                                 start_new_phase = true;
645                         }
646
647                         // Compute shaders currently always end phases.
648                         // (We might loosen this up in some cases in the future.)
649                         if (deps[i]->effect->is_compute_shader()) {
650                                 start_new_phase = true;
651                         }
652
653                         // Propagate information about needing mipmaps down the chain,
654                         // breaking the phase if we notice an incompatibility.
655                         //
656                         // Note that we cannot do this propagation as a normal pass,
657                         // because it needs information about where the phases end
658                         // (we should not propagate the flag across phases).
659                         if (node->needs_mipmaps) {
660                                 if (deps[i]->effect->num_inputs() == 0) {
661                                         Input *input = static_cast<Input *>(deps[i]->effect);
662                                         start_new_phase |= !input->can_supply_mipmaps();
663                                 } else {
664                                         deps[i]->needs_mipmaps = true;
665                                 }
666                         }
667
668                         if (deps[i]->outgoing_links.size() > 1) {
669                                 if (!deps[i]->effect->is_single_texture()) {
670                                         // More than one effect uses this as the input,
671                                         // and it is not a texture itself.
672                                         // The easiest thing to do (and probably also the safest
673                                         // performance-wise in most cases) is to bounce it to a texture
674                                         // and then let the next passes read from that.
675                                         start_new_phase = true;
676                                 } else {
677                                         assert(deps[i]->effect->num_inputs() == 0);
678
679                                         // For textures, we try to be slightly more clever;
680                                         // if none of our outputs need a bounce, we don't bounce
681                                         // but instead simply use the effect many times.
682                                         //
683                                         // Strictly speaking, we could bounce it for some outputs
684                                         // and use it directly for others, but the processing becomes
685                                         // somewhat simpler if the effect is only used in one such way.
686                                         for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
687                                                 Node *rdep = deps[i]->outgoing_links[j];
688                                                 start_new_phase |= rdep->effect->needs_texture_bounce();
689                                         }
690                                 }
691                         }
692
693                         if (deps[i]->effect->sets_virtual_output_size()) {
694                                 assert(deps[i]->effect->changes_output_size());
695                                 // If the next effect sets a virtual size to rely on OpenGL's
696                                 // bilinear sampling, we'll really need to break the phase here.
697                                 start_new_phase = true;
698                         } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
699                                 // If the next effect changes size and we don't have one-to-one sampling,
700                                 // we also need to break here.
701                                 start_new_phase = true;
702                         }
703
704                         if (start_new_phase) {
705                                 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
706                         } else {
707                                 effects_todo_this_phase.push(deps[i]);
708
709                                 // Propagate the one-to-one status down through the dependency.
710                                 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
711                                         deps[i]->effect->one_to_one_sampling();
712                         }
713                 }
714         }
715
716         // No more effects to do this phase. Take all the ones we have,
717         // and create a GLSL program for it.
718         assert(!phase->effects.empty());
719
720         // Deduplicate the inputs, but don't change the ordering e.g. by sorting;
721         // that would be nondeterministic and thus reduce cacheability.
722         // TODO: Make this even more deterministic.
723         vector<Phase *> dedup_inputs;
724         set<Phase *> seen_inputs;
725         for (size_t i = 0; i < phase->inputs.size(); ++i) {
726                 if (seen_inputs.insert(phase->inputs[i]).second) {
727                         dedup_inputs.push_back(phase->inputs[i]);
728                 }
729         }
730         swap(phase->inputs, dedup_inputs);
731
732         // Allocate samplers for each input.
733         phase->input_samplers.resize(phase->inputs.size());
734
735         // We added the effects from the output and back, but we need to output
736         // them in topological sort order in the shader.
737         phase->effects = topological_sort(phase->effects);
738
739         // Figure out if we need mipmaps or not, and if so, tell the inputs that.
740         phase->input_needs_mipmaps = false;
741         for (unsigned i = 0; i < phase->effects.size(); ++i) {
742                 Node *node = phase->effects[i];
743                 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
744         }
745         for (unsigned i = 0; i < phase->effects.size(); ++i) {
746                 Node *node = phase->effects[i];
747                 if (node->effect->num_inputs() == 0) {
748                         Input *input = static_cast<Input *>(node->effect);
749                         assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
750                         CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
751                 }
752         }
753
754         // Tell each node which phase it ended up in, so that the unit test
755         // can check that the phases were split in the right place.
756         // Note that this ignores that effects may be part of multiple phases;
757         // if the unit tests need to test such cases, we'll reconsider.
758         for (unsigned i = 0; i < phase->effects.size(); ++i) {
759                 phase->effects[i]->containing_phase = phase;
760         }
761
762         // Actually make the shader for this phase.
763         compile_glsl_program(phase);
764
765         // Initialize timers.
766         if (movit_timer_queries_supported) {
767                 phase->time_elapsed_ns = 0;
768                 phase->num_measured_iterations = 0;
769         }
770
771         assert(completed_effects->count(output) == 0);
772         completed_effects->insert(make_pair(output, phase));
773         phases.push_back(phase);
774         return phase;
775 }
776
777 void EffectChain::output_dot(const char *filename)
778 {
779         if (movit_debug_level != MOVIT_DEBUG_ON) {
780                 return;
781         }
782
783         FILE *fp = fopen(filename, "w");
784         if (fp == nullptr) {
785                 perror(filename);
786                 exit(1);
787         }
788
789         fprintf(fp, "digraph G {\n");
790         fprintf(fp, "  output [shape=box label=\"(output)\"];\n");
791         for (unsigned i = 0; i < nodes.size(); ++i) {
792                 // Find out which phase this event belongs to.
793                 vector<int> in_phases;
794                 for (unsigned j = 0; j < phases.size(); ++j) {
795                         const Phase* p = phases[j];
796                         if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
797                                 in_phases.push_back(j);
798                         }
799                 }
800
801                 if (in_phases.empty()) {
802                         fprintf(fp, "  n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
803                 } else if (in_phases.size() == 1) {
804                         fprintf(fp, "  n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
805                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
806                                 (in_phases[0] % 8) + 1);
807                 } else {
808                         // If we had new enough Graphviz, style="wedged" would probably be ideal here.
809                         // But alas.
810                         fprintf(fp, "  n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
811                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
812                                 (in_phases[0] % 8) + 1);
813                 }
814
815                 char from_node_id[256];
816                 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
817
818                 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
819                         char to_node_id[256];
820                         snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
821
822                         vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
823                         output_dot_edge(fp, from_node_id, to_node_id, labels);
824                 }
825
826                 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
827                         // Output node.
828                         vector<string> labels = get_labels_for_edge(nodes[i], nullptr);
829                         output_dot_edge(fp, from_node_id, "output", labels);
830                 }
831         }
832         fprintf(fp, "}\n");
833
834         fclose(fp);
835 }
836
837 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
838 {
839         vector<string> labels;
840
841         if (to != nullptr && to->effect->needs_texture_bounce()) {
842                 labels.push_back("needs_bounce");
843         }
844         if (from->effect->changes_output_size()) {
845                 labels.push_back("resize");
846         }
847
848         switch (from->output_color_space) {
849         case COLORSPACE_INVALID:
850                 labels.push_back("spc[invalid]");
851                 break;
852         case COLORSPACE_REC_601_525:
853                 labels.push_back("spc[rec601-525]");
854                 break;
855         case COLORSPACE_REC_601_625:
856                 labels.push_back("spc[rec601-625]");
857                 break;
858         default:
859                 break;
860         }
861
862         switch (from->output_gamma_curve) {
863         case GAMMA_INVALID:
864                 labels.push_back("gamma[invalid]");
865                 break;
866         case GAMMA_sRGB:
867                 labels.push_back("gamma[sRGB]");
868                 break;
869         case GAMMA_REC_601:  // and GAMMA_REC_709
870                 labels.push_back("gamma[rec601/709]");
871                 break;
872         default:
873                 break;
874         }
875
876         switch (from->output_alpha_type) {
877         case ALPHA_INVALID:
878                 labels.push_back("alpha[invalid]");
879                 break;
880         case ALPHA_BLANK:
881                 labels.push_back("alpha[blank]");
882                 break;
883         case ALPHA_POSTMULTIPLIED:
884                 labels.push_back("alpha[postmult]");
885                 break;
886         default:
887                 break;
888         }
889
890         return labels;
891 }
892
893 void EffectChain::output_dot_edge(FILE *fp,
894                                   const string &from_node_id,
895                                   const string &to_node_id,
896                                   const vector<string> &labels)
897 {
898         if (labels.empty()) {
899                 fprintf(fp, "  %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
900         } else {
901                 string label = labels[0];
902                 for (unsigned k = 1; k < labels.size(); ++k) {
903                         label += ", " + labels[k];
904                 }
905                 fprintf(fp, "  %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
906         }
907 }
908
909 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
910 {
911         unsigned scaled_width, scaled_height;
912
913         if (float(width) * aspect_denom >= float(height) * aspect_nom) {
914                 // Same aspect, or W/H > aspect (image is wider than the frame).
915                 // In either case, keep width, and adjust height.
916                 scaled_width = width;
917                 scaled_height = lrintf(width * aspect_denom / aspect_nom);
918         } else {
919                 // W/H < aspect (image is taller than the frame), so keep height,
920                 // and adjust width.
921                 scaled_width = lrintf(height * aspect_nom / aspect_denom);
922                 scaled_height = height;
923         }
924
925         // We should be consistently larger or smaller then the existing choice,
926         // since we have the same aspect.
927         assert(!(scaled_width < *output_width && scaled_height > *output_height));
928         assert(!(scaled_height < *output_height && scaled_width > *output_width));
929
930         if (scaled_width >= *output_width && scaled_height >= *output_height) {
931                 *output_width = scaled_width;
932                 *output_height = scaled_height;
933         }
934 }
935
936 // Propagate input texture sizes throughout, and inform effects downstream.
937 // (Like a lot of other code, we depend on effects being in topological order.)
938 void EffectChain::inform_input_sizes(Phase *phase)
939 {
940         // All effects that have a defined size (inputs and RTT inputs)
941         // get that. Reset all others.
942         for (unsigned i = 0; i < phase->effects.size(); ++i) {
943                 Node *node = phase->effects[i];
944                 if (node->effect->num_inputs() == 0) {
945                         Input *input = static_cast<Input *>(node->effect);
946                         node->output_width = input->get_width();
947                         node->output_height = input->get_height();
948                         assert(node->output_width != 0);
949                         assert(node->output_height != 0);
950                 } else {
951                         node->output_width = node->output_height = 0;
952                 }
953         }
954         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
955                 Phase *input = phase->inputs[i];
956                 input->output_node->output_width = input->virtual_output_width;
957                 input->output_node->output_height = input->virtual_output_height;
958                 assert(input->output_node->output_width != 0);
959                 assert(input->output_node->output_height != 0);
960         }
961
962         // Now propagate from the inputs towards the end, and inform as we go.
963         // The rules are simple:
964         //
965         //   1. Don't touch effects that already have given sizes (ie., inputs
966         //      or effects that change the output size).
967         //   2. If all of your inputs have the same size, that will be your output size.
968         //   3. Otherwise, your output size is 0x0.
969         for (unsigned i = 0; i < phase->effects.size(); ++i) {
970                 Node *node = phase->effects[i];
971                 if (node->effect->num_inputs() == 0) {
972                         continue;
973                 }
974                 unsigned this_output_width = 0;
975                 unsigned this_output_height = 0;
976                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
977                         Node *input = node->incoming_links[j];
978                         node->effect->inform_input_size(j, input->output_width, input->output_height);
979                         if (j == 0) {
980                                 this_output_width = input->output_width;
981                                 this_output_height = input->output_height;
982                         } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
983                                 // Inputs disagree.
984                                 this_output_width = 0;
985                                 this_output_height = 0;
986                         }
987                 }
988                 if (node->effect->changes_output_size()) {
989                         // We cannot call get_output_size() before we've done inform_input_size()
990                         // on all inputs.
991                         unsigned real_width, real_height;
992                         node->effect->get_output_size(&real_width, &real_height,
993                                                       &node->output_width, &node->output_height);
994                         assert(node->effect->sets_virtual_output_size() ||
995                                (real_width == node->output_width &&
996                                 real_height == node->output_height));
997                 } else {
998                         node->output_width = this_output_width;
999                         node->output_height = this_output_height;
1000                 }
1001         }
1002 }
1003
1004 // Note: You should call inform_input_sizes() before this, as the last effect's
1005 // desired output size might change based on the inputs.
1006 void EffectChain::find_output_size(Phase *phase)
1007 {
1008         Node *output_node = phase->effects.back();
1009
1010         // If the last effect explicitly sets an output size, use that.
1011         if (output_node->effect->changes_output_size()) {
1012                 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
1013                                                      &phase->virtual_output_width, &phase->virtual_output_height);
1014                 assert(output_node->effect->sets_virtual_output_size() ||
1015                        (phase->output_width == phase->virtual_output_width &&
1016                         phase->output_height == phase->virtual_output_height));
1017                 return;
1018         }
1019
1020         // If all effects have the same size, use that.
1021         unsigned output_width = 0, output_height = 0;
1022         bool all_inputs_same_size = true;
1023
1024         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1025                 Phase *input = phase->inputs[i];
1026                 assert(input->output_width != 0);
1027                 assert(input->output_height != 0);
1028                 if (output_width == 0 && output_height == 0) {
1029                         output_width = input->virtual_output_width;
1030                         output_height = input->virtual_output_height;
1031                 } else if (output_width != input->virtual_output_width ||
1032                            output_height != input->virtual_output_height) {
1033                         all_inputs_same_size = false;
1034                 }
1035         }
1036         for (unsigned i = 0; i < phase->effects.size(); ++i) {
1037                 Effect *effect = phase->effects[i]->effect;
1038                 if (effect->num_inputs() != 0) {
1039                         continue;
1040                 }
1041
1042                 Input *input = static_cast<Input *>(effect);
1043                 if (output_width == 0 && output_height == 0) {
1044                         output_width = input->get_width();
1045                         output_height = input->get_height();
1046                 } else if (output_width != input->get_width() ||
1047                            output_height != input->get_height()) {
1048                         all_inputs_same_size = false;
1049                 }
1050         }
1051
1052         if (all_inputs_same_size) {
1053                 assert(output_width != 0);
1054                 assert(output_height != 0);
1055                 phase->virtual_output_width = phase->output_width = output_width;
1056                 phase->virtual_output_height = phase->output_height = output_height;
1057                 return;
1058         }
1059
1060         // If not, fit all the inputs into the current aspect, and select the largest one. 
1061         output_width = 0;
1062         output_height = 0;
1063         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1064                 Phase *input = phase->inputs[i];
1065                 assert(input->output_width != 0);
1066                 assert(input->output_height != 0);
1067                 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
1068         }
1069         for (unsigned i = 0; i < phase->effects.size(); ++i) {
1070                 Effect *effect = phase->effects[i]->effect;
1071                 if (effect->num_inputs() != 0) {
1072                         continue;
1073                 }
1074
1075                 Input *input = static_cast<Input *>(effect);
1076                 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
1077         }
1078         assert(output_width != 0);
1079         assert(output_height != 0);
1080         phase->virtual_output_width = phase->output_width = output_width;
1081         phase->virtual_output_height = phase->output_height = output_height;
1082 }
1083
1084 void EffectChain::sort_all_nodes_topologically()
1085 {
1086         nodes = topological_sort(nodes);
1087 }
1088
1089 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
1090 {
1091         set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
1092         vector<Node *> sorted_list;
1093         for (unsigned i = 0; i < nodes.size(); ++i) {
1094                 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
1095         }
1096         reverse(sorted_list.begin(), sorted_list.end());
1097         return sorted_list;
1098 }
1099
1100 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
1101 {
1102         if (nodes_left_to_visit->count(node) == 0) {
1103                 return;
1104         }
1105         nodes_left_to_visit->erase(node);
1106         for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
1107                 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
1108         }
1109         sorted_list->push_back(node);
1110 }
1111
1112 void EffectChain::find_color_spaces_for_inputs()
1113 {
1114         for (unsigned i = 0; i < nodes.size(); ++i) {
1115                 Node *node = nodes[i];
1116                 if (node->disabled) {
1117                         continue;
1118                 }
1119                 if (node->incoming_links.size() == 0) {
1120                         Input *input = static_cast<Input *>(node->effect);
1121                         node->output_color_space = input->get_color_space();
1122                         node->output_gamma_curve = input->get_gamma_curve();
1123
1124                         Effect::AlphaHandling alpha_handling = input->alpha_handling();
1125                         switch (alpha_handling) {
1126                         case Effect::OUTPUT_BLANK_ALPHA:
1127                                 node->output_alpha_type = ALPHA_BLANK;
1128                                 break;
1129                         case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
1130                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1131                                 break;
1132                         case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
1133                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1134                                 break;
1135                         case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
1136                         case Effect::DONT_CARE_ALPHA_TYPE:
1137                         default:
1138                                 assert(false);
1139                         }
1140
1141                         if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
1142                                 assert(node->output_gamma_curve == GAMMA_LINEAR);
1143                         }
1144                 }
1145         }
1146 }
1147
1148 // Propagate gamma and color space information as far as we can in the graph.
1149 // The rules are simple: Anything where all the inputs agree, get that as
1150 // output as well. Anything else keeps having *_INVALID.
1151 void EffectChain::propagate_gamma_and_color_space()
1152 {
1153         // We depend on going through the nodes in order.
1154         sort_all_nodes_topologically();
1155
1156         for (unsigned i = 0; i < nodes.size(); ++i) {
1157                 Node *node = nodes[i];
1158                 if (node->disabled) {
1159                         continue;
1160                 }
1161                 assert(node->incoming_links.size() == node->effect->num_inputs());
1162                 if (node->incoming_links.size() == 0) {
1163                         assert(node->output_color_space != COLORSPACE_INVALID);
1164                         assert(node->output_gamma_curve != GAMMA_INVALID);
1165                         continue;
1166                 }
1167
1168                 Colorspace color_space = node->incoming_links[0]->output_color_space;
1169                 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1170                 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1171                         if (node->incoming_links[j]->output_color_space != color_space) {
1172                                 color_space = COLORSPACE_INVALID;
1173                         }
1174                         if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1175                                 gamma_curve = GAMMA_INVALID;
1176                         }
1177                 }
1178
1179                 // The conversion effects already have their outputs set correctly,
1180                 // so leave them alone.
1181                 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1182                         node->output_color_space = color_space;
1183                 }               
1184                 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1185                     node->effect->effect_type_id() != "GammaExpansionEffect") {
1186                         node->output_gamma_curve = gamma_curve;
1187                 }               
1188         }
1189 }
1190
1191 // Propagate alpha information as far as we can in the graph.
1192 // Similar to propagate_gamma_and_color_space().
1193 void EffectChain::propagate_alpha()
1194 {
1195         // We depend on going through the nodes in order.
1196         sort_all_nodes_topologically();
1197
1198         for (unsigned i = 0; i < nodes.size(); ++i) {
1199                 Node *node = nodes[i];
1200                 if (node->disabled) {
1201                         continue;
1202                 }
1203                 assert(node->incoming_links.size() == node->effect->num_inputs());
1204                 if (node->incoming_links.size() == 0) {
1205                         assert(node->output_alpha_type != ALPHA_INVALID);
1206                         continue;
1207                 }
1208
1209                 // The alpha multiplication/division effects are special cases.
1210                 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1211                         assert(node->incoming_links.size() == 1);
1212                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1213                         node->output_alpha_type = ALPHA_PREMULTIPLIED;
1214                         continue;
1215                 }
1216                 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1217                         assert(node->incoming_links.size() == 1);
1218                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1219                         node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1220                         continue;
1221                 }
1222
1223                 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1224                 // because they are the only one that _need_ postmultiplied alpha.
1225                 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1226                     node->effect->effect_type_id() == "GammaExpansionEffect") {
1227                         assert(node->incoming_links.size() == 1);
1228                         if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1229                                 node->output_alpha_type = ALPHA_BLANK;
1230                         } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1231                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1232                         } else {
1233                                 node->output_alpha_type = ALPHA_INVALID;
1234                         }
1235                         continue;
1236                 }
1237
1238                 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1239                 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1240                 // taken care of above. Rationale: Even if you could imagine
1241                 // e.g. an effect that took in an image and set alpha=1.0
1242                 // unconditionally, it wouldn't make any sense to have it as
1243                 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1244                 // got its input pre- or postmultiplied, so it wouldn't know
1245                 // whether to divide away the old alpha or not.
1246                 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1247                 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1248                        alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1249                        alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1250
1251                 // If the node has multiple inputs, check that they are all valid and
1252                 // the same.
1253                 bool any_invalid = false;
1254                 bool any_premultiplied = false;
1255                 bool any_postmultiplied = false;
1256
1257                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1258                         switch (node->incoming_links[j]->output_alpha_type) {
1259                         case ALPHA_INVALID:
1260                                 any_invalid = true;
1261                                 break;
1262                         case ALPHA_BLANK:
1263                                 // Blank is good as both pre- and postmultiplied alpha,
1264                                 // so just ignore it.
1265                                 break;
1266                         case ALPHA_PREMULTIPLIED:
1267                                 any_premultiplied = true;
1268                                 break;
1269                         case ALPHA_POSTMULTIPLIED:
1270                                 any_postmultiplied = true;
1271                                 break;
1272                         default:
1273                                 assert(false);
1274                         }
1275                 }
1276
1277                 if (any_invalid) {
1278                         node->output_alpha_type = ALPHA_INVALID;
1279                         continue;
1280                 }
1281
1282                 // Inputs must be of the same type.
1283                 if (any_premultiplied && any_postmultiplied) {
1284                         node->output_alpha_type = ALPHA_INVALID;
1285                         continue;
1286                 }
1287
1288                 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1289                     alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1290                         // This combination (requiring premultiplied alpha, but _not_ requiring
1291                         // linear light) is illegal, since the combination of premultiplied alpha
1292                         // and nonlinear inputs is meaningless.
1293                         assert(node->effect->needs_linear_light());
1294
1295                         // If the effect has asked for premultiplied alpha, check that it has got it.
1296                         if (any_postmultiplied) {
1297                                 node->output_alpha_type = ALPHA_INVALID;
1298                         } else if (!any_premultiplied &&
1299                                    alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1300                                 // Blank input alpha, and the effect preserves blank alpha.
1301                                 node->output_alpha_type = ALPHA_BLANK;
1302                         } else {
1303                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1304                         }
1305                 } else {
1306                         // OK, all inputs are the same, and this effect is not going
1307                         // to change it.
1308                         assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1309                         if (any_premultiplied) {
1310                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1311                         } else if (any_postmultiplied) {
1312                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1313                         } else {
1314                                 node->output_alpha_type = ALPHA_BLANK;
1315                         }
1316                 }
1317         }
1318 }
1319
1320 bool EffectChain::node_needs_colorspace_fix(Node *node)
1321 {
1322         if (node->disabled) {
1323                 return false;
1324         }
1325         if (node->effect->num_inputs() == 0) {
1326                 return false;
1327         }
1328
1329         // propagate_gamma_and_color_space() has already set our output
1330         // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1331         if (node->output_color_space == COLORSPACE_INVALID) {
1332                 return true;
1333         }
1334         return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1335 }
1336
1337 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1338 // the graph. Our strategy is not always optimal, but quite simple:
1339 // Find an effect that's as early as possible where the inputs are of
1340 // unacceptable colorspaces (that is, either different, or, if the effect only
1341 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1342 // propagate the information anew, and repeat until there are no more such
1343 // effects.
1344 void EffectChain::fix_internal_color_spaces()
1345 {
1346         unsigned colorspace_propagation_pass = 0;
1347         bool found_any;
1348         do {
1349                 found_any = false;
1350                 for (unsigned i = 0; i < nodes.size(); ++i) {
1351                         Node *node = nodes[i];
1352                         if (!node_needs_colorspace_fix(node)) {
1353                                 continue;
1354                         }
1355
1356                         // Go through each input that is not sRGB, and insert
1357                         // a colorspace conversion after it.
1358                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1359                                 Node *input = node->incoming_links[j];
1360                                 assert(input->output_color_space != COLORSPACE_INVALID);
1361                                 if (input->output_color_space == COLORSPACE_sRGB) {
1362                                         continue;
1363                                 }
1364                                 Node *conversion = add_node(new ColorspaceConversionEffect());
1365                                 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1366                                 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1367                                 conversion->output_color_space = COLORSPACE_sRGB;
1368                                 replace_sender(input, conversion);
1369                                 connect_nodes(input, conversion);
1370                         }
1371
1372                         // Re-sort topologically, and propagate the new information.
1373                         propagate_gamma_and_color_space();
1374                         
1375                         found_any = true;
1376                         break;
1377                 }
1378         
1379                 char filename[256];
1380                 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1381                 output_dot(filename);
1382                 assert(colorspace_propagation_pass < 100);
1383         } while (found_any);
1384
1385         for (unsigned i = 0; i < nodes.size(); ++i) {
1386                 Node *node = nodes[i];
1387                 if (node->disabled) {
1388                         continue;
1389                 }
1390                 assert(node->output_color_space != COLORSPACE_INVALID);
1391         }
1392 }
1393
1394 bool EffectChain::node_needs_alpha_fix(Node *node)
1395 {
1396         if (node->disabled) {
1397                 return false;
1398         }
1399
1400         // propagate_alpha() has already set our output to ALPHA_INVALID if the
1401         // inputs differ or we are otherwise in mismatch, so we can rely on that.
1402         return (node->output_alpha_type == ALPHA_INVALID);
1403 }
1404
1405 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1406 // the graph. Similar to fix_internal_color_spaces().
1407 void EffectChain::fix_internal_alpha(unsigned step)
1408 {
1409         unsigned alpha_propagation_pass = 0;
1410         bool found_any;
1411         do {
1412                 found_any = false;
1413                 for (unsigned i = 0; i < nodes.size(); ++i) {
1414                         Node *node = nodes[i];
1415                         if (!node_needs_alpha_fix(node)) {
1416                                 continue;
1417                         }
1418
1419                         // If we need to fix up GammaExpansionEffect, then clearly something
1420                         // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1421                         // is meaningless.
1422                         assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1423
1424                         AlphaType desired_type = ALPHA_PREMULTIPLIED;
1425
1426                         // GammaCompressionEffect is special; it needs postmultiplied alpha.
1427                         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1428                                 assert(node->incoming_links.size() == 1);
1429                                 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1430                                 desired_type = ALPHA_POSTMULTIPLIED;
1431                         }
1432
1433                         // Go through each input that is not premultiplied alpha, and insert
1434                         // a conversion before it.
1435                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1436                                 Node *input = node->incoming_links[j];
1437                                 assert(input->output_alpha_type != ALPHA_INVALID);
1438                                 if (input->output_alpha_type == desired_type ||
1439                                     input->output_alpha_type == ALPHA_BLANK) {
1440                                         continue;
1441                                 }
1442                                 Node *conversion;
1443                                 if (desired_type == ALPHA_PREMULTIPLIED) {
1444                                         conversion = add_node(new AlphaMultiplicationEffect());
1445                                 } else {
1446                                         conversion = add_node(new AlphaDivisionEffect());
1447                                 }
1448                                 conversion->output_alpha_type = desired_type;
1449                                 replace_sender(input, conversion);
1450                                 connect_nodes(input, conversion);
1451                         }
1452
1453                         // Re-sort topologically, and propagate the new information.
1454                         propagate_gamma_and_color_space();
1455                         propagate_alpha();
1456                         
1457                         found_any = true;
1458                         break;
1459                 }
1460         
1461                 char filename[256];
1462                 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1463                 output_dot(filename);
1464                 assert(alpha_propagation_pass < 100);
1465         } while (found_any);
1466
1467         for (unsigned i = 0; i < nodes.size(); ++i) {
1468                 Node *node = nodes[i];
1469                 if (node->disabled) {
1470                         continue;
1471                 }
1472                 assert(node->output_alpha_type != ALPHA_INVALID);
1473         }
1474 }
1475
1476 // Make so that the output is in the desired color space.
1477 void EffectChain::fix_output_color_space()
1478 {
1479         Node *output = find_output_node();
1480         if (output->output_color_space != output_format.color_space) {
1481                 Node *conversion = add_node(new ColorspaceConversionEffect());
1482                 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1483                 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1484                 conversion->output_color_space = output_format.color_space;
1485                 connect_nodes(output, conversion);
1486                 propagate_alpha();
1487                 propagate_gamma_and_color_space();
1488         }
1489 }
1490
1491 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1492 void EffectChain::fix_output_alpha()
1493 {
1494         Node *output = find_output_node();
1495         assert(output->output_alpha_type != ALPHA_INVALID);
1496         if (output->output_alpha_type == ALPHA_BLANK) {
1497                 // No alpha output, so we don't care.
1498                 return;
1499         }
1500         if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1501             output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1502                 Node *conversion = add_node(new AlphaDivisionEffect());
1503                 connect_nodes(output, conversion);
1504                 propagate_alpha();
1505                 propagate_gamma_and_color_space();
1506         }
1507         if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1508             output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1509                 Node *conversion = add_node(new AlphaMultiplicationEffect());
1510                 connect_nodes(output, conversion);
1511                 propagate_alpha();
1512                 propagate_gamma_and_color_space();
1513         }
1514 }
1515
1516 bool EffectChain::node_needs_gamma_fix(Node *node)
1517 {
1518         if (node->disabled) {
1519                 return false;
1520         }
1521
1522         // Small hack since the output is not an explicit node:
1523         // If we are the last node and our output is in the wrong
1524         // space compared to EffectChain's output, we need to fix it.
1525         // This will only take us to linear, but fix_output_gamma()
1526         // will come and take us to the desired output gamma
1527         // if it is needed.
1528         //
1529         // This needs to be before everything else, since it could
1530         // even apply to inputs (if they are the only effect).
1531         if (node->outgoing_links.empty() &&
1532             node->output_gamma_curve != output_format.gamma_curve &&
1533             node->output_gamma_curve != GAMMA_LINEAR) {
1534                 return true;
1535         }
1536
1537         if (node->effect->num_inputs() == 0) {
1538                 return false;
1539         }
1540
1541         // propagate_gamma_and_color_space() has already set our output
1542         // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1543         // except for GammaCompressionEffect.
1544         if (node->output_gamma_curve == GAMMA_INVALID) {
1545                 return true;
1546         }
1547         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1548                 assert(node->incoming_links.size() == 1);
1549                 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1550         }
1551
1552         return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1553 }
1554
1555 // Very similar to fix_internal_color_spaces(), but for gamma.
1556 // There is one difference, though; before we start adding conversion nodes,
1557 // we see if we can get anything out of asking the sources to deliver
1558 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1559 // does that part, while fix_internal_gamma_by_inserting_nodes()
1560 // inserts nodes as needed afterwards.
1561 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1562 {
1563         unsigned gamma_propagation_pass = 0;
1564         bool found_any;
1565         do {
1566                 found_any = false;
1567                 for (unsigned i = 0; i < nodes.size(); ++i) {
1568                         Node *node = nodes[i];
1569                         if (!node_needs_gamma_fix(node)) {
1570                                 continue;
1571                         }
1572
1573                         // See if all inputs can give us linear gamma. If not, leave it.
1574                         vector<Node *> nonlinear_inputs;
1575                         find_all_nonlinear_inputs(node, &nonlinear_inputs);
1576                         assert(!nonlinear_inputs.empty());
1577
1578                         bool all_ok = true;
1579                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1580                                 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1581                                 all_ok &= input->can_output_linear_gamma();
1582                         }
1583
1584                         if (!all_ok) {
1585                                 continue;
1586                         }
1587
1588                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1589                                 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1590                                 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1591                         }
1592
1593                         // Re-sort topologically, and propagate the new information.
1594                         propagate_gamma_and_color_space();
1595                         
1596                         found_any = true;
1597                         break;
1598                 }
1599         
1600                 char filename[256];
1601                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1602                 output_dot(filename);
1603                 assert(gamma_propagation_pass < 100);
1604         } while (found_any);
1605 }
1606
1607 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1608 {
1609         unsigned gamma_propagation_pass = 0;
1610         bool found_any;
1611         do {
1612                 found_any = false;
1613                 for (unsigned i = 0; i < nodes.size(); ++i) {
1614                         Node *node = nodes[i];
1615                         if (!node_needs_gamma_fix(node)) {
1616                                 continue;
1617                         }
1618
1619                         // Special case: We could be an input and still be asked to
1620                         // fix our gamma; if so, we should be the only node
1621                         // (as node_needs_gamma_fix() would only return true in
1622                         // for an input in that case). That means we should insert
1623                         // a conversion node _after_ ourselves.
1624                         if (node->incoming_links.empty()) {
1625                                 assert(node->outgoing_links.empty());
1626                                 Node *conversion = add_node(new GammaExpansionEffect());
1627                                 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1628                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1629                                 connect_nodes(node, conversion);
1630                         }
1631
1632                         // If not, go through each input that is not linear gamma,
1633                         // and insert a gamma conversion after it.
1634                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1635                                 Node *input = node->incoming_links[j];
1636                                 assert(input->output_gamma_curve != GAMMA_INVALID);
1637                                 if (input->output_gamma_curve == GAMMA_LINEAR) {
1638                                         continue;
1639                                 }
1640                                 Node *conversion = add_node(new GammaExpansionEffect());
1641                                 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1642                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1643                                 replace_sender(input, conversion);
1644                                 connect_nodes(input, conversion);
1645                         }
1646
1647                         // Re-sort topologically, and propagate the new information.
1648                         propagate_alpha();
1649                         propagate_gamma_and_color_space();
1650                         
1651                         found_any = true;
1652                         break;
1653                 }
1654         
1655                 char filename[256];
1656                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1657                 output_dot(filename);
1658                 assert(gamma_propagation_pass < 100);
1659         } while (found_any);
1660
1661         for (unsigned i = 0; i < nodes.size(); ++i) {
1662                 Node *node = nodes[i];
1663                 if (node->disabled) {
1664                         continue;
1665                 }
1666                 assert(node->output_gamma_curve != GAMMA_INVALID);
1667         }
1668 }
1669
1670 // Make so that the output is in the desired gamma.
1671 // Note that this assumes linear input gamma, so it might create the need
1672 // for another pass of fix_internal_gamma().
1673 void EffectChain::fix_output_gamma()
1674 {
1675         Node *output = find_output_node();
1676         if (output->output_gamma_curve != output_format.gamma_curve) {
1677                 Node *conversion = add_node(new GammaCompressionEffect());
1678                 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1679                 conversion->output_gamma_curve = output_format.gamma_curve;
1680                 connect_nodes(output, conversion);
1681         }
1682 }
1683
1684 // If the user has requested Y'CbCr output, we need to do this conversion
1685 // _after_ GammaCompressionEffect etc., but before dither (see below).
1686 // This is because Y'CbCr, with the exception of a special optional mode
1687 // in Rec. 2020 (which we currently don't support), is defined to work on
1688 // gamma-encoded data.
1689 void EffectChain::add_ycbcr_conversion_if_needed()
1690 {
1691         assert(output_color_rgba || num_output_color_ycbcr > 0);
1692         if (num_output_color_ycbcr == 0) {
1693                 return;
1694         }
1695         Node *output = find_output_node();
1696         ycbcr_conversion_effect_node = add_node(new YCbCrConversionEffect(output_ycbcr_format, output_ycbcr_type));
1697         connect_nodes(output, ycbcr_conversion_effect_node);
1698 }
1699         
1700 // If the user has requested dither, add a DitherEffect right at the end
1701 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1702 // since dither is about the only effect that can _not_ be done in linear space.
1703 void EffectChain::add_dither_if_needed()
1704 {
1705         if (num_dither_bits == 0) {
1706                 return;
1707         }
1708         Node *output = find_output_node();
1709         Node *dither = add_node(new DitherEffect());
1710         CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1711         connect_nodes(output, dither);
1712
1713         dither_effect = dither->effect;
1714 }
1715
1716 // Compute shaders can't output to the framebuffer, so if the last
1717 // phase ends in a compute shader, add a dummy phase at the end that
1718 // only blits directly from the temporary texture.
1719 //
1720 // TODO: Add an API for rendering directly to textures, for the cases
1721 // where we're only rendering to an FBO anyway.
1722 void EffectChain::add_dummy_effect_if_needed()
1723 {
1724         Node *output = find_output_node();
1725         if (output->effect->is_compute_shader()) {
1726                 Node *dummy = add_node(new IdentityEffect());
1727                 connect_nodes(output, dummy);
1728                 has_dummy_effect = true;
1729         }
1730 }
1731
1732 // Find the output node. This is, simply, one that has no outgoing links.
1733 // If there are multiple ones, the graph is malformed (we do not support
1734 // multiple outputs right now).
1735 Node *EffectChain::find_output_node()
1736 {
1737         vector<Node *> output_nodes;
1738         for (unsigned i = 0; i < nodes.size(); ++i) {
1739                 Node *node = nodes[i];
1740                 if (node->disabled) {
1741                         continue;
1742                 }
1743                 if (node->outgoing_links.empty()) {
1744                         output_nodes.push_back(node);
1745                 }
1746         }
1747         assert(output_nodes.size() == 1);
1748         return output_nodes[0];
1749 }
1750
1751 void EffectChain::finalize()
1752 {
1753         // Output the graph as it is before we do any conversions on it.
1754         output_dot("step0-start.dot");
1755
1756         // Give each effect in turn a chance to rewrite its own part of the graph.
1757         // Note that if more effects are added as part of this, they will be
1758         // picked up as part of the same for loop, since they are added at the end.
1759         for (unsigned i = 0; i < nodes.size(); ++i) {
1760                 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1761         }
1762         output_dot("step1-rewritten.dot");
1763
1764         find_color_spaces_for_inputs();
1765         output_dot("step2-input-colorspace.dot");
1766
1767         propagate_alpha();
1768         output_dot("step3-propagated-alpha.dot");
1769
1770         propagate_gamma_and_color_space();
1771         output_dot("step4-propagated-all.dot");
1772
1773         fix_internal_color_spaces();
1774         fix_internal_alpha(6);
1775         fix_output_color_space();
1776         output_dot("step7-output-colorspacefix.dot");
1777         fix_output_alpha();
1778         output_dot("step8-output-alphafix.dot");
1779
1780         // Note that we need to fix gamma after colorspace conversion,
1781         // because colorspace conversions might create needs for gamma conversions.
1782         // Also, we need to run an extra pass of fix_internal_gamma() after 
1783         // fixing the output gamma, as we only have conversions to/from linear,
1784         // and fix_internal_alpha() since GammaCompressionEffect needs
1785         // postmultiplied input.
1786         fix_internal_gamma_by_asking_inputs(9);
1787         fix_internal_gamma_by_inserting_nodes(10);
1788         fix_output_gamma();
1789         output_dot("step11-output-gammafix.dot");
1790         propagate_alpha();
1791         output_dot("step12-output-alpha-propagated.dot");
1792         fix_internal_alpha(13);
1793         output_dot("step14-output-alpha-fixed.dot");
1794         fix_internal_gamma_by_asking_inputs(15);
1795         fix_internal_gamma_by_inserting_nodes(16);
1796
1797         output_dot("step17-before-ycbcr.dot");
1798         add_ycbcr_conversion_if_needed();
1799
1800         output_dot("step18-before-dither.dot");
1801         add_dither_if_needed();
1802
1803         output_dot("step19-before-dummy-effect.dot");
1804         add_dummy_effect_if_needed();
1805
1806         output_dot("step20-final.dot");
1807         
1808         // Construct all needed GLSL programs, starting at the output.
1809         // We need to keep track of which effects have already been computed,
1810         // as an effect with multiple users could otherwise be calculated
1811         // multiple times.
1812         map<Node *, Phase *> completed_effects;
1813         construct_phase(find_output_node(), &completed_effects);
1814
1815         output_dot("step21-split-to-phases.dot");
1816
1817         assert(phases[0]->inputs.empty());
1818         
1819         finalized = true;
1820 }
1821
1822 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1823 {
1824         // Save original viewport.
1825         GLuint x = 0, y = 0;
1826
1827         if (width == 0 && height == 0) {
1828                 GLint viewport[4];
1829                 glGetIntegerv(GL_VIEWPORT, viewport);
1830                 x = viewport[0];
1831                 y = viewport[1];
1832                 width = viewport[2];
1833                 height = viewport[3];
1834         }
1835
1836         render(dest_fbo, {}, x, y, width, height);
1837 }
1838
1839 void EffectChain::render_to_texture(const vector<DestinationTexture> &destinations, unsigned width, unsigned height)
1840 {
1841         assert(finalized);
1842         assert(!destinations.empty());
1843
1844         if (!has_dummy_effect) {
1845                 // We don't end in a compute shader, so there's nothing specific for us to do.
1846                 // Create an FBO for this set of textures, and just render to that.
1847                 GLuint texnums[4] = { 0, 0, 0, 0 };
1848                 for (unsigned i = 0; i < destinations.size() && i < 4; ++i) {
1849                         texnums[i] = destinations[i].texnum;
1850                 }
1851                 GLuint dest_fbo = resource_pool->create_fbo(texnums[0], texnums[1], texnums[2], texnums[3]);
1852                 render(dest_fbo, {}, 0, 0, width, height);
1853                 resource_pool->release_fbo(dest_fbo);
1854         } else {
1855                 render((GLuint)-1, destinations, 0, 0, width, height);
1856         }
1857 }
1858
1859 void EffectChain::render(GLuint dest_fbo, const vector<DestinationTexture> &destinations, unsigned x, unsigned y, unsigned width, unsigned height)
1860 {
1861         assert(finalized);
1862         assert(destinations.size() <= 1);
1863
1864         // This needs to be set anew, in case we are coming from a different context
1865         // from when we initialized.
1866         check_error();
1867         glDisable(GL_DITHER);
1868         check_error();
1869
1870         const bool final_srgb = glIsEnabled(GL_FRAMEBUFFER_SRGB);
1871         check_error();
1872         bool current_srgb = final_srgb;
1873
1874         // Basic state.
1875         check_error();
1876         glDisable(GL_BLEND);
1877         check_error();
1878         glDisable(GL_DEPTH_TEST);
1879         check_error();
1880         glDepthMask(GL_FALSE);
1881         check_error();
1882
1883         set<Phase *> generated_mipmaps;
1884
1885         // We choose the simplest option of having one texture per output,
1886         // since otherwise this turns into an (albeit simple) register allocation problem.
1887         map<Phase *, GLuint> output_textures;
1888
1889         size_t num_phases = phases.size();
1890         if (destinations.empty()) {
1891                 assert(dest_fbo != (GLuint)-1);
1892         } else {
1893                 assert(has_dummy_effect);
1894                 assert(x == 0);
1895                 assert(y == 0);
1896                 assert(num_phases >= 2);
1897                 assert(!phases.back()->is_compute_shader);
1898                 assert(phases.back()->effects.size() == 1);
1899                 assert(phases.back()->effects[0]->effect->effect_type_id() == "IdentityEffect");
1900
1901                 // We are rendering to a set of textures, so we can run the compute shader
1902                 // directly and skip the dummy phase.
1903                 --num_phases;
1904         }
1905
1906         for (unsigned phase_num = 0; phase_num < num_phases; ++phase_num) {
1907                 Phase *phase = phases[phase_num];
1908
1909                 if (do_phase_timing) {
1910                         GLuint timer_query_object;
1911                         if (phase->timer_query_objects_free.empty()) {
1912                                 glGenQueries(1, &timer_query_object);
1913                         } else {
1914                                 timer_query_object = phase->timer_query_objects_free.front();
1915                                 phase->timer_query_objects_free.pop_front();
1916                         }
1917                         glBeginQuery(GL_TIME_ELAPSED, timer_query_object);
1918                         phase->timer_query_objects_running.push_back(timer_query_object);
1919                 }
1920                 bool last_phase = (phase_num == num_phases - 1);
1921                 if (phase_num == num_phases - 1) {
1922                         // Last phase goes to the output the user specified.
1923                         if (!phase->is_compute_shader) {
1924                                 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1925                                 check_error();
1926                                 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1927                                 assert(status == GL_FRAMEBUFFER_COMPLETE);
1928                                 glViewport(x, y, width, height);
1929                         }
1930                         if (dither_effect != nullptr) {
1931                                 CHECK(dither_effect->set_int("output_width", width));
1932                                 CHECK(dither_effect->set_int("output_height", height));
1933                         }
1934                 }
1935
1936                 // Enable sRGB rendering for intermediates in case we are
1937                 // rendering to an sRGB format.
1938                 // TODO: Support this for compute shaders.
1939                 bool needs_srgb = last_phase ? final_srgb : true;
1940                 if (needs_srgb && !current_srgb) {
1941                         glEnable(GL_FRAMEBUFFER_SRGB);
1942                         check_error();
1943                         current_srgb = true;
1944                 } else if (!needs_srgb && current_srgb) {
1945                         glDisable(GL_FRAMEBUFFER_SRGB);
1946                         check_error();
1947                         current_srgb = true;
1948                 }
1949
1950                 // Find a texture for this phase.
1951                 inform_input_sizes(phase);
1952                 find_output_size(phase);
1953                 vector<DestinationTexture> phase_destinations;
1954                 if (!last_phase) {
1955                         GLuint tex_num = resource_pool->create_2d_texture(intermediate_format, phase->output_width, phase->output_height);
1956                         output_textures.insert(make_pair(phase, tex_num));
1957                         phase_destinations.push_back(DestinationTexture{ tex_num, intermediate_format });
1958
1959                         // The output texture needs to have valid state to be written to by a compute shader.
1960                         glActiveTexture(GL_TEXTURE0);
1961                         check_error();
1962                         glBindTexture(GL_TEXTURE_2D, tex_num);
1963                         check_error();
1964                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1965                         check_error();
1966                 } else if (phase->is_compute_shader) {
1967                         assert(!destinations.empty());
1968                         phase_destinations = destinations;
1969                 }
1970
1971                 execute_phase(phase, output_textures, phase_destinations, &generated_mipmaps);
1972                 if (do_phase_timing) {
1973                         glEndQuery(GL_TIME_ELAPSED);
1974                 }
1975         }
1976
1977         for (const auto &phase_and_texnum : output_textures) {
1978                 resource_pool->release_2d_texture(phase_and_texnum.second);
1979         }
1980
1981         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1982         check_error();
1983         glUseProgram(0);
1984         check_error();
1985
1986         glBindBuffer(GL_ARRAY_BUFFER, 0);
1987         check_error();
1988         glBindVertexArray(0);
1989         check_error();
1990
1991         if (do_phase_timing) {
1992                 // Get back the timer queries.
1993                 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1994                         Phase *phase = phases[phase_num];
1995                         for (auto timer_it = phase->timer_query_objects_running.cbegin();
1996                              timer_it != phase->timer_query_objects_running.cend(); ) {
1997                                 GLint timer_query_object = *timer_it;
1998                                 GLint available;
1999                                 glGetQueryObjectiv(timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
2000                                 if (available) {
2001                                         GLuint64 time_elapsed;
2002                                         glGetQueryObjectui64v(timer_query_object, GL_QUERY_RESULT, &time_elapsed);
2003                                         phase->time_elapsed_ns += time_elapsed;
2004                                         ++phase->num_measured_iterations;
2005                                         phase->timer_query_objects_free.push_back(timer_query_object);
2006                                         phase->timer_query_objects_running.erase(timer_it++);
2007                                 } else {
2008                                         ++timer_it;
2009                                 }
2010                         }
2011                 }
2012         }
2013 }
2014
2015 void EffectChain::enable_phase_timing(bool enable)
2016 {
2017         if (enable) {
2018                 assert(movit_timer_queries_supported);
2019         }
2020         this->do_phase_timing = enable;
2021 }
2022
2023 void EffectChain::reset_phase_timing()
2024 {
2025         for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2026                 Phase *phase = phases[phase_num];
2027                 phase->time_elapsed_ns = 0;
2028                 phase->num_measured_iterations = 0;
2029         }
2030 }
2031
2032 void EffectChain::print_phase_timing()
2033 {
2034         double total_time_ms = 0.0;
2035         for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2036                 Phase *phase = phases[phase_num];
2037                 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
2038                 printf("Phase %d: %5.1f ms  [", phase_num, avg_time_ms);
2039                 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
2040                         if (effect_num != 0) {
2041                                 printf(", ");
2042                         }
2043                         printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
2044                 }
2045                 printf("]\n");
2046                 total_time_ms += avg_time_ms;
2047         }
2048         printf("Total:   %5.1f ms\n", total_time_ms);
2049 }
2050
2051 void EffectChain::execute_phase(Phase *phase,
2052                                 const map<Phase *, GLuint> &output_textures,
2053                                 const std::vector<DestinationTexture> &destinations,
2054                                 set<Phase *> *generated_mipmaps)
2055 {
2056         // Set up RTT inputs for this phase.
2057         for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
2058                 glActiveTexture(GL_TEXTURE0 + sampler);
2059                 Phase *input = phase->inputs[sampler];
2060                 input->output_node->bound_sampler_num = sampler;
2061                 const auto it = output_textures.find(input);
2062                 assert(it != output_textures.end());
2063                 glBindTexture(GL_TEXTURE_2D, it->second);
2064                 check_error();
2065                 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
2066                         glGenerateMipmap(GL_TEXTURE_2D);
2067                         check_error();
2068                         generated_mipmaps->insert(input);
2069                 }
2070                 setup_rtt_sampler(sampler, phase->input_needs_mipmaps);
2071                 phase->input_samplers[sampler] = sampler;  // Bind the sampler to the right uniform.
2072         }
2073
2074         GLuint instance_program_num = resource_pool->use_glsl_program(phase->glsl_program_num);
2075         check_error();
2076
2077         // And now the output.
2078         GLuint fbo = 0;
2079         if (phase->is_compute_shader) {
2080                 assert(!destinations.empty());
2081
2082                 // This is currently the only place where we use image units,
2083                 // so we can always start at 0. TODO: Support multiple destinations.
2084                 phase->outbuf_image_unit = 0;
2085                 glBindImageTexture(phase->outbuf_image_unit, destinations[0].texnum, 0, GL_FALSE, 0, GL_WRITE_ONLY, destinations[0].format);
2086                 check_error();
2087                 phase->inv_output_size.x = 1.0f / phase->output_width;
2088                 phase->inv_output_size.y = 1.0f / phase->output_height;
2089                 phase->output_texcoord_adjust.x = 0.5f / phase->output_width;
2090                 phase->output_texcoord_adjust.y = 0.5f / phase->output_height;
2091         } else if (!destinations.empty()) {
2092                 assert(destinations.size() == 1);
2093                 fbo = resource_pool->create_fbo(destinations[0].texnum);
2094                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
2095                 glViewport(0, 0, phase->output_width, phase->output_height);
2096         }
2097
2098         // Give the required parameters to all the effects.
2099         unsigned sampler_num = phase->inputs.size();
2100         for (unsigned i = 0; i < phase->effects.size(); ++i) {
2101                 Node *node = phase->effects[i];
2102                 unsigned old_sampler_num = sampler_num;
2103                 node->effect->set_gl_state(instance_program_num, phase->effect_ids[node], &sampler_num);
2104                 check_error();
2105
2106                 if (node->effect->is_single_texture()) {
2107                         assert(sampler_num - old_sampler_num == 1);
2108                         node->bound_sampler_num = old_sampler_num;
2109                 } else {
2110                         node->bound_sampler_num = -1;
2111                 }
2112         }
2113
2114         if (phase->is_compute_shader) {
2115                 unsigned x, y, z;
2116                 phase->output_node->effect->get_compute_dimensions(phase->output_width, phase->output_height, &x, &y, &z);
2117
2118                 // Uniforms need to come after set_gl_state() _and_ get_compute_dimensions(),
2119                 // since they can be updated from there.
2120                 setup_uniforms(phase);
2121                 glDispatchCompute(x, y, z);
2122                 check_error();
2123                 glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_TEXTURE_UPDATE_BARRIER_BIT);
2124                 check_error();
2125         } else {
2126                 // Uniforms need to come after set_gl_state(), since they can be updated
2127                 // from there.
2128                 setup_uniforms(phase);
2129
2130                 // Bind the vertex data.
2131                 GLuint vao = resource_pool->create_vec2_vao(phase->attribute_indexes, vbo);
2132                 glBindVertexArray(vao);
2133
2134                 glDrawArrays(GL_TRIANGLES, 0, 3);
2135                 check_error();
2136
2137                 resource_pool->release_vec2_vao(vao);
2138         }
2139         
2140         for (unsigned i = 0; i < phase->effects.size(); ++i) {
2141                 Node *node = phase->effects[i];
2142                 node->effect->clear_gl_state();
2143         }
2144
2145         resource_pool->unuse_glsl_program(instance_program_num);
2146
2147         if (fbo != 0) {
2148                 resource_pool->release_fbo(fbo);
2149         }
2150 }
2151
2152 void EffectChain::setup_uniforms(Phase *phase)
2153 {
2154         // TODO: Use UBO blocks.
2155         for (size_t i = 0; i < phase->uniforms_image2d.size(); ++i) {
2156                 const Uniform<int> &uniform = phase->uniforms_image2d[i];
2157                 if (uniform.location != -1) {
2158                         glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2159                 }
2160         }
2161         for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
2162                 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
2163                 if (uniform.location != -1) {
2164                         glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2165                 }
2166         }
2167         for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
2168                 const Uniform<bool> &uniform = phase->uniforms_bool[i];
2169                 assert(uniform.num_values == 1);
2170                 if (uniform.location != -1) {
2171                         glUniform1i(uniform.location, *uniform.value);
2172                 }
2173         }
2174         for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
2175                 const Uniform<int> &uniform = phase->uniforms_int[i];
2176                 if (uniform.location != -1) {
2177                         glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2178                 }
2179         }
2180         for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
2181                 const Uniform<float> &uniform = phase->uniforms_float[i];
2182                 if (uniform.location != -1) {
2183                         glUniform1fv(uniform.location, uniform.num_values, uniform.value);
2184                 }
2185         }
2186         for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
2187                 const Uniform<float> &uniform = phase->uniforms_vec2[i];
2188                 if (uniform.location != -1) {
2189                         glUniform2fv(uniform.location, uniform.num_values, uniform.value);
2190                 }
2191         }
2192         for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
2193                 const Uniform<float> &uniform = phase->uniforms_vec3[i];
2194                 if (uniform.location != -1) {
2195                         glUniform3fv(uniform.location, uniform.num_values, uniform.value);
2196                 }
2197         }
2198         for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
2199                 const Uniform<float> &uniform = phase->uniforms_vec4[i];
2200                 if (uniform.location != -1) {
2201                         glUniform4fv(uniform.location, uniform.num_values, uniform.value);
2202                 }
2203         }
2204         for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
2205                 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
2206                 assert(uniform.num_values == 1);
2207                 if (uniform.location != -1) {
2208                         // Convert to float (GLSL has no double matrices).
2209                         float matrixf[9];
2210                         for (unsigned y = 0; y < 3; ++y) {
2211                                 for (unsigned x = 0; x < 3; ++x) {
2212                                         matrixf[y + x * 3] = (*uniform.value)(y, x);
2213                                 }
2214                         }
2215                         glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
2216                 }
2217         }
2218 }
2219
2220 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
2221 {
2222         glActiveTexture(GL_TEXTURE0 + sampler_num);
2223         check_error();
2224         if (use_mipmaps) {
2225                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
2226                 check_error();
2227         } else {
2228                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2229                 check_error();
2230         }
2231         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2232         check_error();
2233         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2234         check_error();
2235 }
2236
2237 }  // namespace movit