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