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