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