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