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