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