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