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