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