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