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