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