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