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