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