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