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