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