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