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