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