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