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