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