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