Add support for multiple shader models.
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <epoxy/gl.h>
4 #include <assert.h>
5 #include <locale.h>
6 #include <math.h>
7 #include <stddef.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <algorithm>
12 #include <set>
13 #include <stack>
14 #include <utility>
15 #include <vector>
16
17 #include "alpha_division_effect.h"
18 #include "alpha_multiplication_effect.h"
19 #include "colorspace_conversion_effect.h"
20 #include "dither_effect.h"
21 #include "effect.h"
22 #include "effect_chain.h"
23 #include "gamma_compression_effect.h"
24 #include "gamma_expansion_effect.h"
25 #include "init.h"
26 #include "input.h"
27 #include "resource_pool.h"
28 #include "util.h"
29
30 using namespace std;
31
32 namespace movit {
33
34 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
35         : aspect_nom(aspect_nom),
36           aspect_denom(aspect_denom),
37           dither_effect(NULL),
38           num_dither_bits(0),
39           finalized(false),
40           resource_pool(resource_pool) {
41         if (resource_pool == NULL) {
42                 this->resource_pool = new ResourcePool();
43                 owns_resource_pool = true;
44         } else {
45                 owns_resource_pool = false;
46         }
47 }
48
49 EffectChain::~EffectChain()
50 {
51         for (unsigned i = 0; i < nodes.size(); ++i) {
52                 delete nodes[i]->effect;
53                 delete nodes[i];
54         }
55         for (unsigned i = 0; i < phases.size(); ++i) {
56                 glBindVertexArray(phases[i]->vao);
57                 check_error();
58
59                 cleanup_vertex_attribute(phases[i]->glsl_program_num, "position", phases[i]->position_vbo);
60                 cleanup_vertex_attribute(phases[i]->glsl_program_num, "texcoord", phases[i]->texcoord_vbo);
61
62                 glBindVertexArray(0);
63                 check_error();
64
65                 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
66                 delete phases[i];
67         }
68         if (owns_resource_pool) {
69                 delete resource_pool;
70         }
71         for (map<void *, GLuint>::const_iterator fbo_it = fbos.begin();
72              fbo_it != fbos.end(); ++fbo_it) {
73                 glDeleteFramebuffers(1, &fbo_it->second);
74                 check_error();
75         }
76 }
77
78 Input *EffectChain::add_input(Input *input)
79 {
80         assert(!finalized);
81         inputs.push_back(input);
82         add_node(input);
83         return input;
84 }
85
86 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
87 {
88         assert(!finalized);
89         output_format = format;
90         output_alpha_format = alpha_format;
91 }
92
93 Node *EffectChain::add_node(Effect *effect)
94 {
95         for (unsigned i = 0; i < nodes.size(); ++i) {
96                 assert(nodes[i]->effect != effect);
97         }
98
99         Node *node = new Node;
100         node->effect = effect;
101         node->disabled = false;
102         node->output_color_space = COLORSPACE_INVALID;
103         node->output_gamma_curve = GAMMA_INVALID;
104         node->output_alpha_type = ALPHA_INVALID;
105
106         nodes.push_back(node);
107         node_map[effect] = node;
108         effect->inform_added(this);
109         return node;
110 }
111
112 void EffectChain::connect_nodes(Node *sender, Node *receiver)
113 {
114         sender->outgoing_links.push_back(receiver);
115         receiver->incoming_links.push_back(sender);
116 }
117
118 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
119 {
120         new_receiver->incoming_links = old_receiver->incoming_links;
121         old_receiver->incoming_links.clear();
122         
123         for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
124                 Node *sender = new_receiver->incoming_links[i];
125                 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
126                         if (sender->outgoing_links[j] == old_receiver) {
127                                 sender->outgoing_links[j] = new_receiver;
128                         }
129                 }
130         }       
131 }
132
133 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
134 {
135         new_sender->outgoing_links = old_sender->outgoing_links;
136         old_sender->outgoing_links.clear();
137         
138         for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
139                 Node *receiver = new_sender->outgoing_links[i];
140                 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
141                         if (receiver->incoming_links[j] == old_sender) {
142                                 receiver->incoming_links[j] = new_sender;
143                         }
144                 }
145         }       
146 }
147
148 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
149 {
150         for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
151                 if (sender->outgoing_links[i] == receiver) {
152                         sender->outgoing_links[i] = middle;
153                         middle->incoming_links.push_back(sender);
154                 }
155         }
156         for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
157                 if (receiver->incoming_links[i] == sender) {
158                         receiver->incoming_links[i] = middle;
159                         middle->outgoing_links.push_back(receiver);
160                 }
161         }
162
163         assert(middle->incoming_links.size() == middle->effect->num_inputs());
164 }
165
166 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
167 {
168         assert(node->effect->needs_texture_bounce());
169         assert(input_num < node->incoming_links.size());
170         assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
171         assert(node->incoming_links[input_num]->bound_sampler_num < 8);
172         return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
173 }
174
175 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
176 {
177         if (node->output_gamma_curve == GAMMA_LINEAR &&
178             node->effect->effect_type_id() != "GammaCompressionEffect") {
179                 return;
180         }
181         if (node->effect->num_inputs() == 0) {
182                 nonlinear_inputs->push_back(node);
183         } else {
184                 assert(node->effect->num_inputs() == node->incoming_links.size());
185                 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
186                         find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
187                 }
188         }
189 }
190
191 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
192 {
193         assert(!finalized);
194         assert(inputs.size() == effect->num_inputs());
195         Node *node = add_node(effect);
196         for (unsigned i = 0; i < inputs.size(); ++i) {
197                 assert(node_map.count(inputs[i]) != 0);
198                 connect_nodes(node_map[inputs[i]], node);
199         }
200         return effect;
201 }
202
203 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
204 string replace_prefix(const string &text, const string &prefix)
205 {
206         string output;
207         size_t start = 0;
208
209         while (start < text.size()) {
210                 size_t pos = text.find("PREFIX(", start);
211                 if (pos == string::npos) {
212                         output.append(text.substr(start, string::npos));
213                         break;
214                 }
215
216                 output.append(text.substr(start, pos - start));
217                 output.append(prefix);
218                 output.append("_");
219
220                 pos += strlen("PREFIX(");
221         
222                 // Output stuff until we find the matching ), which we then eat.
223                 int depth = 1;
224                 size_t end_arg_pos = pos;
225                 while (end_arg_pos < text.size()) {
226                         if (text[end_arg_pos] == '(') {
227                                 ++depth;
228                         } else if (text[end_arg_pos] == ')') {
229                                 --depth;
230                                 if (depth == 0) {
231                                         break;
232                                 }
233                         }
234                         ++end_arg_pos;
235                 }
236                 output.append(text.substr(pos, end_arg_pos - pos));
237                 ++end_arg_pos;
238                 assert(depth == 0);
239                 start = end_arg_pos;
240         }
241         return output;
242 }
243
244 void EffectChain::compile_glsl_program(Phase *phase)
245 {
246         string frag_shader = read_version_dependent_file("header", "frag");
247
248         // Create functions for all the texture inputs that we need.
249         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
250                 Node *input = phase->inputs[i]->output_node;
251                 char effect_id[256];
252                 sprintf(effect_id, "in%u", i);
253                 phase->effect_ids.insert(make_pair(input, effect_id));
254         
255                 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
256                 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
257                 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
258                 frag_shader += "}\n";
259                 frag_shader += "\n";
260         }
261
262         for (unsigned i = 0; i < phase->effects.size(); ++i) {
263                 Node *node = phase->effects[i];
264                 char effect_id[256];
265                 sprintf(effect_id, "eff%u", i);
266                 phase->effect_ids.insert(make_pair(node, effect_id));
267
268                 if (node->incoming_links.size() == 1) {
269                         frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
270                 } else {
271                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
272                                 char buf[256];
273                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
274                                 frag_shader += buf;
275                         }
276                 }
277         
278                 frag_shader += "\n";
279                 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
280                 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), effect_id);
281                 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
282                 frag_shader += "#undef PREFIX\n";
283                 frag_shader += "#undef FUNCNAME\n";
284                 if (node->incoming_links.size() == 1) {
285                         frag_shader += "#undef INPUT\n";
286                 } else {
287                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
288                                 char buf[256];
289                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
290                                 frag_shader += buf;
291                         }
292                 }
293                 frag_shader += "\n";
294         }
295         frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
296         frag_shader.append(read_version_dependent_file("footer", "frag"));
297
298         string vert_shader = read_version_dependent_file("vs", "vert");
299         phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
300
301         // Prepare the geometry for the fullscreen quad used in this phase.
302         // (We have separate VAOs per shader, since the bindings can in theory
303         // be different.)
304         float vertices[] = {
305                 0.0f, 1.0f,
306                 0.0f, 0.0f,
307                 1.0f, 1.0f,
308                 1.0f, 0.0f
309         };
310
311         glGenVertexArrays(1, &phase->vao);
312         check_error();
313         glBindVertexArray(phase->vao);
314         check_error();
315
316         phase->position_vbo = fill_vertex_attribute(phase->glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
317         phase->texcoord_vbo = fill_vertex_attribute(phase->glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices);  // Same as vertices.
318
319         glBindVertexArray(0);
320         check_error();
321 }
322
323 // Construct GLSL programs, starting at the given effect and following
324 // the chain from there. We end a program every time we come to an effect
325 // marked as "needs texture bounce", one that is used by multiple other
326 // effects, every time an effect wants to change the output size,
327 // and of course at the end.
328 //
329 // We follow a quite simple depth-first search from the output, although
330 // without recursing explicitly within each phase.
331 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
332 {
333         if (completed_effects->count(output)) {
334                 return (*completed_effects)[output];
335         }
336
337         Phase *phase = new Phase;
338         phase->output_node = output;
339
340         // Effects that we have yet to calculate, but that we know should
341         // be in the current phase.
342         stack<Node *> effects_todo_this_phase;
343         effects_todo_this_phase.push(output);
344
345         while (!effects_todo_this_phase.empty()) {
346                 Node *node = effects_todo_this_phase.top();
347                 effects_todo_this_phase.pop();
348
349                 // This should currently only happen for effects that are inputs
350                 // (either true inputs or phase outputs). We special-case inputs,
351                 // and then deduplicate phase outputs below.
352                 if (node->effect->num_inputs() == 0) {
353                         if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
354                                 continue;
355                         }
356                 } else {
357                         assert(completed_effects->count(node) == 0);
358                 }
359
360                 phase->effects.push_back(node);
361
362                 // Find all the dependencies of this effect, and add them to the stack.
363                 vector<Node *> deps = node->incoming_links;
364                 assert(node->effect->num_inputs() == deps.size());
365                 for (unsigned i = 0; i < deps.size(); ++i) {
366                         bool start_new_phase = false;
367
368                         if (node->effect->needs_texture_bounce() &&
369                             !deps[i]->effect->is_single_texture()) {
370                                 start_new_phase = true;
371                         }
372
373                         if (deps[i]->outgoing_links.size() > 1) {
374                                 if (!deps[i]->effect->is_single_texture()) {
375                                         // More than one effect uses this as the input,
376                                         // and it is not a texture itself.
377                                         // The easiest thing to do (and probably also the safest
378                                         // performance-wise in most cases) is to bounce it to a texture
379                                         // and then let the next passes read from that.
380                                         start_new_phase = true;
381                                 } else {
382                                         assert(deps[i]->effect->num_inputs() == 0);
383
384                                         // For textures, we try to be slightly more clever;
385                                         // if none of our outputs need a bounce, we don't bounce
386                                         // but instead simply use the effect many times.
387                                         //
388                                         // Strictly speaking, we could bounce it for some outputs
389                                         // and use it directly for others, but the processing becomes
390                                         // somewhat simpler if the effect is only used in one such way.
391                                         for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
392                                                 Node *rdep = deps[i]->outgoing_links[j];
393                                                 start_new_phase |= rdep->effect->needs_texture_bounce();
394                                         }
395                                 }
396                         }
397
398                         if (deps[i]->effect->changes_output_size()) {
399                                 start_new_phase = true;
400                         }
401
402                         if (start_new_phase) {
403                                 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
404                         } else {
405                                 effects_todo_this_phase.push(deps[i]);
406                         }
407                 }
408         }
409
410         // No more effects to do this phase. Take all the ones we have,
411         // and create a GLSL program for it.
412         assert(!phase->effects.empty());
413
414         // Deduplicate the inputs.
415         sort(phase->inputs.begin(), phase->inputs.end());
416         phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
417
418         // We added the effects from the output and back, but we need to output
419         // them in topological sort order in the shader.
420         phase->effects = topological_sort(phase->effects);
421
422         // Figure out if we need mipmaps or not, and if so, tell the inputs that.
423         phase->input_needs_mipmaps = false;
424         for (unsigned i = 0; i < phase->effects.size(); ++i) {
425                 Node *node = phase->effects[i];
426                 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
427         }
428         for (unsigned i = 0; i < phase->effects.size(); ++i) {
429                 Node *node = phase->effects[i];
430                 if (node->effect->num_inputs() == 0) {
431                         CHECK(node->effect->set_int("needs_mipmaps", phase->input_needs_mipmaps));
432                 }
433         }
434
435         // Actually make the shader for this phase.
436         compile_glsl_program(phase);
437
438         assert(completed_effects->count(output) == 0);
439         completed_effects->insert(make_pair(output, phase));
440         phases.push_back(phase);
441         return phase;
442 }
443
444 void EffectChain::output_dot(const char *filename)
445 {
446         if (movit_debug_level != MOVIT_DEBUG_ON) {
447                 return;
448         }
449
450         FILE *fp = fopen(filename, "w");
451         if (fp == NULL) {
452                 perror(filename);
453                 exit(1);
454         }
455
456         fprintf(fp, "digraph G {\n");
457         fprintf(fp, "  output [shape=box label=\"(output)\"];\n");
458         for (unsigned i = 0; i < nodes.size(); ++i) {
459                 // Find out which phase this event belongs to.
460                 vector<int> in_phases;
461                 for (unsigned j = 0; j < phases.size(); ++j) {
462                         const Phase* p = phases[j];
463                         if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
464                                 in_phases.push_back(j);
465                         }
466                 }
467
468                 if (in_phases.empty()) {
469                         fprintf(fp, "  n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
470                 } else if (in_phases.size() == 1) {
471                         fprintf(fp, "  n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
472                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
473                                 (in_phases[0] % 8) + 1);
474                 } else {
475                         // If we had new enough Graphviz, style="wedged" would probably be ideal here.
476                         // But alas.
477                         fprintf(fp, "  n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
478                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
479                                 (in_phases[0] % 8) + 1);
480                 }
481
482                 char from_node_id[256];
483                 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
484
485                 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
486                         char to_node_id[256];
487                         snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
488
489                         vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
490                         output_dot_edge(fp, from_node_id, to_node_id, labels);
491                 }
492
493                 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
494                         // Output node.
495                         vector<string> labels = get_labels_for_edge(nodes[i], NULL);
496                         output_dot_edge(fp, from_node_id, "output", labels);
497                 }
498         }
499         fprintf(fp, "}\n");
500
501         fclose(fp);
502 }
503
504 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
505 {
506         vector<string> labels;
507
508         if (to != NULL && to->effect->needs_texture_bounce()) {
509                 labels.push_back("needs_bounce");
510         }
511         if (from->effect->changes_output_size()) {
512                 labels.push_back("resize");
513         }
514
515         switch (from->output_color_space) {
516         case COLORSPACE_INVALID:
517                 labels.push_back("spc[invalid]");
518                 break;
519         case COLORSPACE_REC_601_525:
520                 labels.push_back("spc[rec601-525]");
521                 break;
522         case COLORSPACE_REC_601_625:
523                 labels.push_back("spc[rec601-625]");
524                 break;
525         default:
526                 break;
527         }
528
529         switch (from->output_gamma_curve) {
530         case GAMMA_INVALID:
531                 labels.push_back("gamma[invalid]");
532                 break;
533         case GAMMA_sRGB:
534                 labels.push_back("gamma[sRGB]");
535                 break;
536         case GAMMA_REC_601:  // and GAMMA_REC_709
537                 labels.push_back("gamma[rec601/709]");
538                 break;
539         default:
540                 break;
541         }
542
543         switch (from->output_alpha_type) {
544         case ALPHA_INVALID:
545                 labels.push_back("alpha[invalid]");
546                 break;
547         case ALPHA_BLANK:
548                 labels.push_back("alpha[blank]");
549                 break;
550         case ALPHA_POSTMULTIPLIED:
551                 labels.push_back("alpha[postmult]");
552                 break;
553         default:
554                 break;
555         }
556
557         return labels;
558 }
559
560 void EffectChain::output_dot_edge(FILE *fp,
561                                   const string &from_node_id,
562                                   const string &to_node_id,
563                                   const vector<string> &labels)
564 {
565         if (labels.empty()) {
566                 fprintf(fp, "  %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
567         } else {
568                 string label = labels[0];
569                 for (unsigned k = 1; k < labels.size(); ++k) {
570                         label += ", " + labels[k];
571                 }
572                 fprintf(fp, "  %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
573         }
574 }
575
576 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
577 {
578         unsigned scaled_width, scaled_height;
579
580         if (float(width) * aspect_denom >= float(height) * aspect_nom) {
581                 // Same aspect, or W/H > aspect (image is wider than the frame).
582                 // In either case, keep width, and adjust height.
583                 scaled_width = width;
584                 scaled_height = lrintf(width * aspect_denom / aspect_nom);
585         } else {
586                 // W/H < aspect (image is taller than the frame), so keep height,
587                 // and adjust width.
588                 scaled_width = lrintf(height * aspect_nom / aspect_denom);
589                 scaled_height = height;
590         }
591
592         // We should be consistently larger or smaller then the existing choice,
593         // since we have the same aspect.
594         assert(!(scaled_width < *output_width && scaled_height > *output_height));
595         assert(!(scaled_height < *output_height && scaled_width > *output_width));
596
597         if (scaled_width >= *output_width && scaled_height >= *output_height) {
598                 *output_width = scaled_width;
599                 *output_height = scaled_height;
600         }
601 }
602
603 // Propagate input texture sizes throughout, and inform effects downstream.
604 // (Like a lot of other code, we depend on effects being in topological order.)
605 void EffectChain::inform_input_sizes(Phase *phase)
606 {
607         // All effects that have a defined size (inputs and RTT inputs)
608         // get that. Reset all others.
609         for (unsigned i = 0; i < phase->effects.size(); ++i) {
610                 Node *node = phase->effects[i];
611                 if (node->effect->num_inputs() == 0) {
612                         Input *input = static_cast<Input *>(node->effect);
613                         node->output_width = input->get_width();
614                         node->output_height = input->get_height();
615                         assert(node->output_width != 0);
616                         assert(node->output_height != 0);
617                 } else {
618                         node->output_width = node->output_height = 0;
619                 }
620         }
621         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
622                 Phase *input = phase->inputs[i];
623                 input->output_node->output_width = input->virtual_output_width;
624                 input->output_node->output_height = input->virtual_output_height;
625                 assert(input->output_node->output_width != 0);
626                 assert(input->output_node->output_height != 0);
627         }
628
629         // Now propagate from the inputs towards the end, and inform as we go.
630         // The rules are simple:
631         //
632         //   1. Don't touch effects that already have given sizes (ie., inputs).
633         //   2. If all of your inputs have the same size, that will be your output size.
634         //   3. Otherwise, your output size is 0x0.
635         for (unsigned i = 0; i < phase->effects.size(); ++i) {
636                 Node *node = phase->effects[i];
637                 if (node->effect->num_inputs() == 0) {
638                         continue;
639                 }
640                 unsigned this_output_width = 0;
641                 unsigned this_output_height = 0;
642                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
643                         Node *input = node->incoming_links[j];
644                         node->effect->inform_input_size(j, input->output_width, input->output_height);
645                         if (j == 0) {
646                                 this_output_width = input->output_width;
647                                 this_output_height = input->output_height;
648                         } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
649                                 // Inputs disagree.
650                                 this_output_width = 0;
651                                 this_output_height = 0;
652                         }
653                 }
654                 node->output_width = this_output_width;
655                 node->output_height = this_output_height;
656         }
657 }
658
659 // Note: You should call inform_input_sizes() before this, as the last effect's
660 // desired output size might change based on the inputs.
661 void EffectChain::find_output_size(Phase *phase)
662 {
663         Node *output_node = phase->effects.back();
664
665         // If the last effect explicitly sets an output size, use that.
666         if (output_node->effect->changes_output_size()) {
667                 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
668                                                      &phase->virtual_output_width, &phase->virtual_output_height);
669                 return;
670         }
671
672         // If all effects have the same size, use that.
673         unsigned output_width = 0, output_height = 0;
674         bool all_inputs_same_size = true;
675
676         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
677                 Phase *input = phase->inputs[i];
678                 assert(input->output_width != 0);
679                 assert(input->output_height != 0);
680                 if (output_width == 0 && output_height == 0) {
681                         output_width = input->virtual_output_width;
682                         output_height = input->virtual_output_height;
683                 } else if (output_width != input->virtual_output_width ||
684                            output_height != input->virtual_output_height) {
685                         all_inputs_same_size = false;
686                 }
687         }
688         for (unsigned i = 0; i < phase->effects.size(); ++i) {
689                 Effect *effect = phase->effects[i]->effect;
690                 if (effect->num_inputs() != 0) {
691                         continue;
692                 }
693
694                 Input *input = static_cast<Input *>(effect);
695                 if (output_width == 0 && output_height == 0) {
696                         output_width = input->get_width();
697                         output_height = input->get_height();
698                 } else if (output_width != input->get_width() ||
699                            output_height != input->get_height()) {
700                         all_inputs_same_size = false;
701                 }
702         }
703
704         if (all_inputs_same_size) {
705                 assert(output_width != 0);
706                 assert(output_height != 0);
707                 phase->virtual_output_width = phase->output_width = output_width;
708                 phase->virtual_output_height = phase->output_height = output_height;
709                 return;
710         }
711
712         // If not, fit all the inputs into the current aspect, and select the largest one. 
713         output_width = 0;
714         output_height = 0;
715         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
716                 Phase *input = phase->inputs[i];
717                 assert(input->output_width != 0);
718                 assert(input->output_height != 0);
719                 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
720         }
721         for (unsigned i = 0; i < phase->effects.size(); ++i) {
722                 Effect *effect = phase->effects[i]->effect;
723                 if (effect->num_inputs() != 0) {
724                         continue;
725                 }
726
727                 Input *input = static_cast<Input *>(effect);
728                 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
729         }
730         assert(output_width != 0);
731         assert(output_height != 0);
732         phase->virtual_output_width = phase->output_width = output_width;
733         phase->virtual_output_height = phase->output_height = output_height;
734 }
735
736 void EffectChain::sort_all_nodes_topologically()
737 {
738         nodes = topological_sort(nodes);
739 }
740
741 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
742 {
743         set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
744         vector<Node *> sorted_list;
745         for (unsigned i = 0; i < nodes.size(); ++i) {
746                 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
747         }
748         reverse(sorted_list.begin(), sorted_list.end());
749         return sorted_list;
750 }
751
752 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
753 {
754         if (nodes_left_to_visit->count(node) == 0) {
755                 return;
756         }
757         nodes_left_to_visit->erase(node);
758         for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
759                 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
760         }
761         sorted_list->push_back(node);
762 }
763
764 void EffectChain::find_color_spaces_for_inputs()
765 {
766         for (unsigned i = 0; i < nodes.size(); ++i) {
767                 Node *node = nodes[i];
768                 if (node->disabled) {
769                         continue;
770                 }
771                 if (node->incoming_links.size() == 0) {
772                         Input *input = static_cast<Input *>(node->effect);
773                         node->output_color_space = input->get_color_space();
774                         node->output_gamma_curve = input->get_gamma_curve();
775
776                         Effect::AlphaHandling alpha_handling = input->alpha_handling();
777                         switch (alpha_handling) {
778                         case Effect::OUTPUT_BLANK_ALPHA:
779                                 node->output_alpha_type = ALPHA_BLANK;
780                                 break;
781                         case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
782                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
783                                 break;
784                         case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
785                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
786                                 break;
787                         case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
788                         case Effect::DONT_CARE_ALPHA_TYPE:
789                         default:
790                                 assert(false);
791                         }
792
793                         if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
794                                 assert(node->output_gamma_curve == GAMMA_LINEAR);
795                         }
796                 }
797         }
798 }
799
800 // Propagate gamma and color space information as far as we can in the graph.
801 // The rules are simple: Anything where all the inputs agree, get that as
802 // output as well. Anything else keeps having *_INVALID.
803 void EffectChain::propagate_gamma_and_color_space()
804 {
805         // We depend on going through the nodes in order.
806         sort_all_nodes_topologically();
807
808         for (unsigned i = 0; i < nodes.size(); ++i) {
809                 Node *node = nodes[i];
810                 if (node->disabled) {
811                         continue;
812                 }
813                 assert(node->incoming_links.size() == node->effect->num_inputs());
814                 if (node->incoming_links.size() == 0) {
815                         assert(node->output_color_space != COLORSPACE_INVALID);
816                         assert(node->output_gamma_curve != GAMMA_INVALID);
817                         continue;
818                 }
819
820                 Colorspace color_space = node->incoming_links[0]->output_color_space;
821                 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
822                 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
823                         if (node->incoming_links[j]->output_color_space != color_space) {
824                                 color_space = COLORSPACE_INVALID;
825                         }
826                         if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
827                                 gamma_curve = GAMMA_INVALID;
828                         }
829                 }
830
831                 // The conversion effects already have their outputs set correctly,
832                 // so leave them alone.
833                 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
834                         node->output_color_space = color_space;
835                 }               
836                 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
837                     node->effect->effect_type_id() != "GammaExpansionEffect") {
838                         node->output_gamma_curve = gamma_curve;
839                 }               
840         }
841 }
842
843 // Propagate alpha information as far as we can in the graph.
844 // Similar to propagate_gamma_and_color_space().
845 void EffectChain::propagate_alpha()
846 {
847         // We depend on going through the nodes in order.
848         sort_all_nodes_topologically();
849
850         for (unsigned i = 0; i < nodes.size(); ++i) {
851                 Node *node = nodes[i];
852                 if (node->disabled) {
853                         continue;
854                 }
855                 assert(node->incoming_links.size() == node->effect->num_inputs());
856                 if (node->incoming_links.size() == 0) {
857                         assert(node->output_alpha_type != ALPHA_INVALID);
858                         continue;
859                 }
860
861                 // The alpha multiplication/division effects are special cases.
862                 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
863                         assert(node->incoming_links.size() == 1);
864                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
865                         node->output_alpha_type = ALPHA_PREMULTIPLIED;
866                         continue;
867                 }
868                 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
869                         assert(node->incoming_links.size() == 1);
870                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
871                         node->output_alpha_type = ALPHA_POSTMULTIPLIED;
872                         continue;
873                 }
874
875                 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
876                 // because they are the only one that _need_ postmultiplied alpha.
877                 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
878                     node->effect->effect_type_id() == "GammaExpansionEffect") {
879                         assert(node->incoming_links.size() == 1);
880                         if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
881                                 node->output_alpha_type = ALPHA_BLANK;
882                         } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
883                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
884                         } else {
885                                 node->output_alpha_type = ALPHA_INVALID;
886                         }
887                         continue;
888                 }
889
890                 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
891                 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
892                 // taken care of above. Rationale: Even if you could imagine
893                 // e.g. an effect that took in an image and set alpha=1.0
894                 // unconditionally, it wouldn't make any sense to have it as
895                 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
896                 // got its input pre- or postmultiplied, so it wouldn't know
897                 // whether to divide away the old alpha or not.
898                 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
899                 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
900                        alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
901                        alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
902
903                 // If the node has multiple inputs, check that they are all valid and
904                 // the same.
905                 bool any_invalid = false;
906                 bool any_premultiplied = false;
907                 bool any_postmultiplied = false;
908
909                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
910                         switch (node->incoming_links[j]->output_alpha_type) {
911                         case ALPHA_INVALID:
912                                 any_invalid = true;
913                                 break;
914                         case ALPHA_BLANK:
915                                 // Blank is good as both pre- and postmultiplied alpha,
916                                 // so just ignore it.
917                                 break;
918                         case ALPHA_PREMULTIPLIED:
919                                 any_premultiplied = true;
920                                 break;
921                         case ALPHA_POSTMULTIPLIED:
922                                 any_postmultiplied = true;
923                                 break;
924                         default:
925                                 assert(false);
926                         }
927                 }
928
929                 if (any_invalid) {
930                         node->output_alpha_type = ALPHA_INVALID;
931                         continue;
932                 }
933
934                 // Inputs must be of the same type.
935                 if (any_premultiplied && any_postmultiplied) {
936                         node->output_alpha_type = ALPHA_INVALID;
937                         continue;
938                 }
939
940                 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
941                     alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
942                         // If the effect has asked for premultiplied alpha, check that it has got it.
943                         if (any_postmultiplied) {
944                                 node->output_alpha_type = ALPHA_INVALID;
945                         } else if (!any_premultiplied &&
946                                    alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
947                                 // Blank input alpha, and the effect preserves blank alpha.
948                                 node->output_alpha_type = ALPHA_BLANK;
949                         } else {
950                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
951                         }
952                 } else {
953                         // OK, all inputs are the same, and this effect is not going
954                         // to change it.
955                         assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
956                         if (any_premultiplied) {
957                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
958                         } else if (any_postmultiplied) {
959                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
960                         } else {
961                                 node->output_alpha_type = ALPHA_BLANK;
962                         }
963                 }
964         }
965 }
966
967 bool EffectChain::node_needs_colorspace_fix(Node *node)
968 {
969         if (node->disabled) {
970                 return false;
971         }
972         if (node->effect->num_inputs() == 0) {
973                 return false;
974         }
975
976         // propagate_gamma_and_color_space() has already set our output
977         // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
978         if (node->output_color_space == COLORSPACE_INVALID) {
979                 return true;
980         }
981         return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
982 }
983
984 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
985 // the graph. Our strategy is not always optimal, but quite simple:
986 // Find an effect that's as early as possible where the inputs are of
987 // unacceptable colorspaces (that is, either different, or, if the effect only
988 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
989 // propagate the information anew, and repeat until there are no more such
990 // effects.
991 void EffectChain::fix_internal_color_spaces()
992 {
993         unsigned colorspace_propagation_pass = 0;
994         bool found_any;
995         do {
996                 found_any = false;
997                 for (unsigned i = 0; i < nodes.size(); ++i) {
998                         Node *node = nodes[i];
999                         if (!node_needs_colorspace_fix(node)) {
1000                                 continue;
1001                         }
1002
1003                         // Go through each input that is not sRGB, and insert
1004                         // a colorspace conversion after it.
1005                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1006                                 Node *input = node->incoming_links[j];
1007                                 assert(input->output_color_space != COLORSPACE_INVALID);
1008                                 if (input->output_color_space == COLORSPACE_sRGB) {
1009                                         continue;
1010                                 }
1011                                 Node *conversion = add_node(new ColorspaceConversionEffect());
1012                                 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1013                                 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1014                                 conversion->output_color_space = COLORSPACE_sRGB;
1015                                 replace_sender(input, conversion);
1016                                 connect_nodes(input, conversion);
1017                         }
1018
1019                         // Re-sort topologically, and propagate the new information.
1020                         propagate_gamma_and_color_space();
1021                         
1022                         found_any = true;
1023                         break;
1024                 }
1025         
1026                 char filename[256];
1027                 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1028                 output_dot(filename);
1029                 assert(colorspace_propagation_pass < 100);
1030         } while (found_any);
1031
1032         for (unsigned i = 0; i < nodes.size(); ++i) {
1033                 Node *node = nodes[i];
1034                 if (node->disabled) {
1035                         continue;
1036                 }
1037                 assert(node->output_color_space != COLORSPACE_INVALID);
1038         }
1039 }
1040
1041 bool EffectChain::node_needs_alpha_fix(Node *node)
1042 {
1043         if (node->disabled) {
1044                 return false;
1045         }
1046
1047         // propagate_alpha() has already set our output to ALPHA_INVALID if the
1048         // inputs differ or we are otherwise in mismatch, so we can rely on that.
1049         return (node->output_alpha_type == ALPHA_INVALID);
1050 }
1051
1052 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1053 // the graph. Similar to fix_internal_color_spaces().
1054 void EffectChain::fix_internal_alpha(unsigned step)
1055 {
1056         unsigned alpha_propagation_pass = 0;
1057         bool found_any;
1058         do {
1059                 found_any = false;
1060                 for (unsigned i = 0; i < nodes.size(); ++i) {
1061                         Node *node = nodes[i];
1062                         if (!node_needs_alpha_fix(node)) {
1063                                 continue;
1064                         }
1065
1066                         // If we need to fix up GammaExpansionEffect, then clearly something
1067                         // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1068                         // is meaningless.
1069                         assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1070
1071                         AlphaType desired_type = ALPHA_PREMULTIPLIED;
1072
1073                         // GammaCompressionEffect is special; it needs postmultiplied alpha.
1074                         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1075                                 assert(node->incoming_links.size() == 1);
1076                                 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1077                                 desired_type = ALPHA_POSTMULTIPLIED;
1078                         }
1079
1080                         // Go through each input that is not premultiplied alpha, and insert
1081                         // a conversion before it.
1082                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1083                                 Node *input = node->incoming_links[j];
1084                                 assert(input->output_alpha_type != ALPHA_INVALID);
1085                                 if (input->output_alpha_type == desired_type ||
1086                                     input->output_alpha_type == ALPHA_BLANK) {
1087                                         continue;
1088                                 }
1089                                 Node *conversion;
1090                                 if (desired_type == ALPHA_PREMULTIPLIED) {
1091                                         conversion = add_node(new AlphaMultiplicationEffect());
1092                                 } else {
1093                                         conversion = add_node(new AlphaDivisionEffect());
1094                                 }
1095                                 conversion->output_alpha_type = desired_type;
1096                                 replace_sender(input, conversion);
1097                                 connect_nodes(input, conversion);
1098                         }
1099
1100                         // Re-sort topologically, and propagate the new information.
1101                         propagate_gamma_and_color_space();
1102                         propagate_alpha();
1103                         
1104                         found_any = true;
1105                         break;
1106                 }
1107         
1108                 char filename[256];
1109                 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1110                 output_dot(filename);
1111                 assert(alpha_propagation_pass < 100);
1112         } while (found_any);
1113
1114         for (unsigned i = 0; i < nodes.size(); ++i) {
1115                 Node *node = nodes[i];
1116                 if (node->disabled) {
1117                         continue;
1118                 }
1119                 assert(node->output_alpha_type != ALPHA_INVALID);
1120         }
1121 }
1122
1123 // Make so that the output is in the desired color space.
1124 void EffectChain::fix_output_color_space()
1125 {
1126         Node *output = find_output_node();
1127         if (output->output_color_space != output_format.color_space) {
1128                 Node *conversion = add_node(new ColorspaceConversionEffect());
1129                 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1130                 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1131                 conversion->output_color_space = output_format.color_space;
1132                 connect_nodes(output, conversion);
1133                 propagate_alpha();
1134                 propagate_gamma_and_color_space();
1135         }
1136 }
1137
1138 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1139 void EffectChain::fix_output_alpha()
1140 {
1141         Node *output = find_output_node();
1142         assert(output->output_alpha_type != ALPHA_INVALID);
1143         if (output->output_alpha_type == ALPHA_BLANK) {
1144                 // No alpha output, so we don't care.
1145                 return;
1146         }
1147         if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1148             output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1149                 Node *conversion = add_node(new AlphaDivisionEffect());
1150                 connect_nodes(output, conversion);
1151                 propagate_alpha();
1152                 propagate_gamma_and_color_space();
1153         }
1154         if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1155             output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1156                 Node *conversion = add_node(new AlphaMultiplicationEffect());
1157                 connect_nodes(output, conversion);
1158                 propagate_alpha();
1159                 propagate_gamma_and_color_space();
1160         }
1161 }
1162
1163 bool EffectChain::node_needs_gamma_fix(Node *node)
1164 {
1165         if (node->disabled) {
1166                 return false;
1167         }
1168
1169         // Small hack since the output is not an explicit node:
1170         // If we are the last node and our output is in the wrong
1171         // space compared to EffectChain's output, we need to fix it.
1172         // This will only take us to linear, but fix_output_gamma()
1173         // will come and take us to the desired output gamma
1174         // if it is needed.
1175         //
1176         // This needs to be before everything else, since it could
1177         // even apply to inputs (if they are the only effect).
1178         if (node->outgoing_links.empty() &&
1179             node->output_gamma_curve != output_format.gamma_curve &&
1180             node->output_gamma_curve != GAMMA_LINEAR) {
1181                 return true;
1182         }
1183
1184         if (node->effect->num_inputs() == 0) {
1185                 return false;
1186         }
1187
1188         // propagate_gamma_and_color_space() has already set our output
1189         // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1190         // except for GammaCompressionEffect.
1191         if (node->output_gamma_curve == GAMMA_INVALID) {
1192                 return true;
1193         }
1194         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1195                 assert(node->incoming_links.size() == 1);
1196                 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1197         }
1198
1199         return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1200 }
1201
1202 // Very similar to fix_internal_color_spaces(), but for gamma.
1203 // There is one difference, though; before we start adding conversion nodes,
1204 // we see if we can get anything out of asking the sources to deliver
1205 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1206 // does that part, while fix_internal_gamma_by_inserting_nodes()
1207 // inserts nodes as needed afterwards.
1208 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1209 {
1210         unsigned gamma_propagation_pass = 0;
1211         bool found_any;
1212         do {
1213                 found_any = false;
1214                 for (unsigned i = 0; i < nodes.size(); ++i) {
1215                         Node *node = nodes[i];
1216                         if (!node_needs_gamma_fix(node)) {
1217                                 continue;
1218                         }
1219
1220                         // See if all inputs can give us linear gamma. If not, leave it.
1221                         vector<Node *> nonlinear_inputs;
1222                         find_all_nonlinear_inputs(node, &nonlinear_inputs);
1223                         assert(!nonlinear_inputs.empty());
1224
1225                         bool all_ok = true;
1226                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1227                                 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1228                                 all_ok &= input->can_output_linear_gamma();
1229                         }
1230
1231                         if (!all_ok) {
1232                                 continue;
1233                         }
1234
1235                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1236                                 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1237                                 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1238                         }
1239
1240                         // Re-sort topologically, and propagate the new information.
1241                         propagate_gamma_and_color_space();
1242                         
1243                         found_any = true;
1244                         break;
1245                 }
1246         
1247                 char filename[256];
1248                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1249                 output_dot(filename);
1250                 assert(gamma_propagation_pass < 100);
1251         } while (found_any);
1252 }
1253
1254 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1255 {
1256         unsigned gamma_propagation_pass = 0;
1257         bool found_any;
1258         do {
1259                 found_any = false;
1260                 for (unsigned i = 0; i < nodes.size(); ++i) {
1261                         Node *node = nodes[i];
1262                         if (!node_needs_gamma_fix(node)) {
1263                                 continue;
1264                         }
1265
1266                         // Special case: We could be an input and still be asked to
1267                         // fix our gamma; if so, we should be the only node
1268                         // (as node_needs_gamma_fix() would only return true in
1269                         // for an input in that case). That means we should insert
1270                         // a conversion node _after_ ourselves.
1271                         if (node->incoming_links.empty()) {
1272                                 assert(node->outgoing_links.empty());
1273                                 Node *conversion = add_node(new GammaExpansionEffect());
1274                                 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1275                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1276                                 connect_nodes(node, conversion);
1277                         }
1278
1279                         // If not, go through each input that is not linear gamma,
1280                         // and insert a gamma conversion after it.
1281                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1282                                 Node *input = node->incoming_links[j];
1283                                 assert(input->output_gamma_curve != GAMMA_INVALID);
1284                                 if (input->output_gamma_curve == GAMMA_LINEAR) {
1285                                         continue;
1286                                 }
1287                                 Node *conversion = add_node(new GammaExpansionEffect());
1288                                 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1289                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1290                                 replace_sender(input, conversion);
1291                                 connect_nodes(input, conversion);
1292                         }
1293
1294                         // Re-sort topologically, and propagate the new information.
1295                         propagate_alpha();
1296                         propagate_gamma_and_color_space();
1297                         
1298                         found_any = true;
1299                         break;
1300                 }
1301         
1302                 char filename[256];
1303                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1304                 output_dot(filename);
1305                 assert(gamma_propagation_pass < 100);
1306         } while (found_any);
1307
1308         for (unsigned i = 0; i < nodes.size(); ++i) {
1309                 Node *node = nodes[i];
1310                 if (node->disabled) {
1311                         continue;
1312                 }
1313                 assert(node->output_gamma_curve != GAMMA_INVALID);
1314         }
1315 }
1316
1317 // Make so that the output is in the desired gamma.
1318 // Note that this assumes linear input gamma, so it might create the need
1319 // for another pass of fix_internal_gamma().
1320 void EffectChain::fix_output_gamma()
1321 {
1322         Node *output = find_output_node();
1323         if (output->output_gamma_curve != output_format.gamma_curve) {
1324                 Node *conversion = add_node(new GammaCompressionEffect());
1325                 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1326                 conversion->output_gamma_curve = output_format.gamma_curve;
1327                 connect_nodes(output, conversion);
1328         }
1329 }
1330         
1331 // If the user has requested dither, add a DitherEffect right at the end
1332 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1333 // since dither is about the only effect that can _not_ be done in linear space.
1334 void EffectChain::add_dither_if_needed()
1335 {
1336         if (num_dither_bits == 0) {
1337                 return;
1338         }
1339         Node *output = find_output_node();
1340         Node *dither = add_node(new DitherEffect());
1341         CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1342         connect_nodes(output, dither);
1343
1344         dither_effect = dither->effect;
1345 }
1346
1347 // Find the output node. This is, simply, one that has no outgoing links.
1348 // If there are multiple ones, the graph is malformed (we do not support
1349 // multiple outputs right now).
1350 Node *EffectChain::find_output_node()
1351 {
1352         vector<Node *> output_nodes;
1353         for (unsigned i = 0; i < nodes.size(); ++i) {
1354                 Node *node = nodes[i];
1355                 if (node->disabled) {
1356                         continue;
1357                 }
1358                 if (node->outgoing_links.empty()) {
1359                         output_nodes.push_back(node);
1360                 }
1361         }
1362         assert(output_nodes.size() == 1);
1363         return output_nodes[0];
1364 }
1365
1366 void EffectChain::finalize()
1367 {
1368         // Save the current locale, and set it to C, so that we can output decimal
1369         // numbers with printf and be sure to get them in the format mandated by GLSL.
1370         char *saved_locale = setlocale(LC_NUMERIC, "C");
1371
1372         // Output the graph as it is before we do any conversions on it.
1373         output_dot("step0-start.dot");
1374
1375         // Give each effect in turn a chance to rewrite its own part of the graph.
1376         // Note that if more effects are added as part of this, they will be
1377         // picked up as part of the same for loop, since they are added at the end.
1378         for (unsigned i = 0; i < nodes.size(); ++i) {
1379                 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1380         }
1381         output_dot("step1-rewritten.dot");
1382
1383         find_color_spaces_for_inputs();
1384         output_dot("step2-input-colorspace.dot");
1385
1386         propagate_alpha();
1387         output_dot("step3-propagated-alpha.dot");
1388
1389         propagate_gamma_and_color_space();
1390         output_dot("step4-propagated-all.dot");
1391
1392         fix_internal_color_spaces();
1393         fix_internal_alpha(6);
1394         fix_output_color_space();
1395         output_dot("step7-output-colorspacefix.dot");
1396         fix_output_alpha();
1397         output_dot("step8-output-alphafix.dot");
1398
1399         // Note that we need to fix gamma after colorspace conversion,
1400         // because colorspace conversions might create needs for gamma conversions.
1401         // Also, we need to run an extra pass of fix_internal_gamma() after 
1402         // fixing the output gamma, as we only have conversions to/from linear,
1403         // and fix_internal_alpha() since GammaCompressionEffect needs
1404         // postmultiplied input.
1405         fix_internal_gamma_by_asking_inputs(9);
1406         fix_internal_gamma_by_inserting_nodes(10);
1407         fix_output_gamma();
1408         output_dot("step11-output-gammafix.dot");
1409         propagate_alpha();
1410         output_dot("step12-output-alpha-propagated.dot");
1411         fix_internal_alpha(13);
1412         output_dot("step14-output-alpha-fixed.dot");
1413         fix_internal_gamma_by_asking_inputs(15);
1414         fix_internal_gamma_by_inserting_nodes(16);
1415
1416         output_dot("step17-before-dither.dot");
1417
1418         add_dither_if_needed();
1419
1420         output_dot("step18-final.dot");
1421         
1422         // Construct all needed GLSL programs, starting at the output.
1423         // We need to keep track of which effects have already been computed,
1424         // as an effect with multiple users could otherwise be calculated
1425         // multiple times.
1426         map<Node *, Phase *> completed_effects;
1427         construct_phase(find_output_node(), &completed_effects);
1428
1429         output_dot("step19-split-to-phases.dot");
1430
1431         assert(phases[0]->inputs.empty());
1432         
1433         finalized = true;
1434         setlocale(LC_NUMERIC, saved_locale);
1435 }
1436
1437 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1438 {
1439         assert(finalized);
1440
1441         // Save original viewport.
1442         GLuint x = 0, y = 0;
1443         GLuint fbo = 0;
1444         void *context = get_gl_context_identifier();
1445
1446         if (width == 0 && height == 0) {
1447                 GLint viewport[4];
1448                 glGetIntegerv(GL_VIEWPORT, viewport);
1449                 x = viewport[0];
1450                 y = viewport[1];
1451                 width = viewport[2];
1452                 height = viewport[3];
1453         }
1454
1455         // Basic state.
1456         glDisable(GL_BLEND);
1457         check_error();
1458         glDisable(GL_DEPTH_TEST);
1459         check_error();
1460         glDepthMask(GL_FALSE);
1461         check_error();
1462
1463         if (phases.size() > 1) {
1464                 if (fbos.count(context) == 0) {
1465                         glGenFramebuffers(1, &fbo);
1466                         check_error();
1467                         fbos.insert(make_pair(context, fbo));
1468                 } else {
1469                         fbo = fbos[context];
1470                 }
1471                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1472                 check_error();
1473         }
1474
1475         set<Phase *> generated_mipmaps;
1476
1477         // We choose the simplest option of having one texture per output,
1478         // since otherwise this turns into an (albeit simple) register allocation problem.
1479         map<Phase *, GLuint> output_textures;
1480
1481         for (unsigned phase = 0; phase < phases.size(); ++phase) {
1482                 // Find a texture for this phase.
1483                 inform_input_sizes(phases[phase]);
1484                 if (phase != phases.size() - 1) {
1485                         find_output_size(phases[phase]);
1486
1487                         GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height);
1488                         output_textures.insert(make_pair(phases[phase], tex_num));
1489                 }
1490
1491                 const GLuint glsl_program_num = phases[phase]->glsl_program_num;
1492                 check_error();
1493                 glUseProgram(glsl_program_num);
1494                 check_error();
1495
1496                 // Set up RTT inputs for this phase.
1497                 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
1498                         glActiveTexture(GL_TEXTURE0 + sampler);
1499                         Phase *input = phases[phase]->inputs[sampler];
1500                         input->output_node->bound_sampler_num = sampler;
1501                         glBindTexture(GL_TEXTURE_2D, output_textures[input]);
1502                         check_error();
1503                         if (phases[phase]->input_needs_mipmaps) {
1504                                 if (generated_mipmaps.count(input) == 0) {
1505                                         glGenerateMipmap(GL_TEXTURE_2D);
1506                                         check_error();
1507                                         generated_mipmaps.insert(input);
1508                                 }
1509                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1510                                 check_error();
1511                         } else {
1512                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1513                                 check_error();
1514                         }
1515                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1516                         check_error();
1517                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1518                         check_error();
1519
1520                         string texture_name = string("tex_") + phases[phase]->effect_ids[input->output_node];
1521                         glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler);
1522                         check_error();
1523                 }
1524
1525                 // And now the output.
1526                 if (phase == phases.size() - 1) {
1527                         // Last phase goes to the output the user specified.
1528                         glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1529                         check_error();
1530                         GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1531                         assert(status == GL_FRAMEBUFFER_COMPLETE);
1532                         glViewport(x, y, width, height);
1533                         if (dither_effect != NULL) {
1534                                 CHECK(dither_effect->set_int("output_width", width));
1535                                 CHECK(dither_effect->set_int("output_height", height));
1536                         }
1537                 } else {
1538                         glFramebufferTexture2D(
1539                                 GL_FRAMEBUFFER,
1540                                 GL_COLOR_ATTACHMENT0,
1541                                 GL_TEXTURE_2D,
1542                                 output_textures[phases[phase]],
1543                                 0);
1544                         check_error();
1545                         GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1546                         assert(status == GL_FRAMEBUFFER_COMPLETE);
1547                         glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
1548                 }
1549
1550                 // Give the required parameters to all the effects.
1551                 unsigned sampler_num = phases[phase]->inputs.size();
1552                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1553                         Node *node = phases[phase]->effects[i];
1554                         unsigned old_sampler_num = sampler_num;
1555                         node->effect->set_gl_state(glsl_program_num, phases[phase]->effect_ids[node], &sampler_num);
1556                         check_error();
1557
1558                         if (node->effect->is_single_texture()) {
1559                                 assert(sampler_num - old_sampler_num == 1);
1560                                 node->bound_sampler_num = old_sampler_num;
1561                         } else {
1562                                 node->bound_sampler_num = -1;
1563                         }
1564                 }
1565
1566                 glBindVertexArray(phases[phase]->vao);
1567                 check_error();
1568                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1569                 check_error();
1570
1571                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1572                         Node *node = phases[phase]->effects[i];
1573                         node->effect->clear_gl_state();
1574                 }
1575         }
1576
1577         for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1578              texture_it != output_textures.end();
1579              ++texture_it) {
1580                 resource_pool->release_2d_texture(texture_it->second);
1581         }
1582
1583         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1584         check_error();
1585         glBindVertexArray(0);
1586         check_error();
1587         glUseProgram(0);
1588         check_error();
1589 }
1590
1591 }  // namespace movit