Drop setting the locale altogether.
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <epoxy/gl.h>
4 #include <assert.h>
5 #include <math.h>
6 #include <stddef.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <algorithm>
11 #include <set>
12 #include <stack>
13 #include <utility>
14 #include <vector>
15
16 #include "alpha_division_effect.h"
17 #include "alpha_multiplication_effect.h"
18 #include "colorspace_conversion_effect.h"
19 #include "dither_effect.h"
20 #include "effect.h"
21 #include "effect_chain.h"
22 #include "gamma_compression_effect.h"
23 #include "gamma_expansion_effect.h"
24 #include "init.h"
25 #include "input.h"
26 #include "resource_pool.h"
27 #include "util.h"
28
29 using namespace std;
30
31 namespace movit {
32
33 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
34         : aspect_nom(aspect_nom),
35           aspect_denom(aspect_denom),
36           dither_effect(NULL),
37           num_dither_bits(0),
38           finalized(false),
39           resource_pool(resource_pool) {
40         if (resource_pool == NULL) {
41                 this->resource_pool = new ResourcePool();
42                 owns_resource_pool = true;
43         } else {
44                 owns_resource_pool = false;
45         }
46 }
47
48 EffectChain::~EffectChain()
49 {
50         for (unsigned i = 0; i < nodes.size(); ++i) {
51                 delete nodes[i]->effect;
52                 delete nodes[i];
53         }
54         for (unsigned i = 0; i < phases.size(); ++i) {
55                 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
56                 delete phases[i];
57         }
58         if (owns_resource_pool) {
59                 delete resource_pool;
60         }
61 }
62
63 Input *EffectChain::add_input(Input *input)
64 {
65         assert(!finalized);
66         inputs.push_back(input);
67         add_node(input);
68         return input;
69 }
70
71 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
72 {
73         assert(!finalized);
74         output_format = format;
75         output_alpha_format = alpha_format;
76 }
77
78 Node *EffectChain::add_node(Effect *effect)
79 {
80         for (unsigned i = 0; i < nodes.size(); ++i) {
81                 assert(nodes[i]->effect != effect);
82         }
83
84         Node *node = new Node;
85         node->effect = effect;
86         node->disabled = false;
87         node->output_color_space = COLORSPACE_INVALID;
88         node->output_gamma_curve = GAMMA_INVALID;
89         node->output_alpha_type = ALPHA_INVALID;
90
91         nodes.push_back(node);
92         node_map[effect] = node;
93         effect->inform_added(this);
94         return node;
95 }
96
97 void EffectChain::connect_nodes(Node *sender, Node *receiver)
98 {
99         sender->outgoing_links.push_back(receiver);
100         receiver->incoming_links.push_back(sender);
101 }
102
103 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
104 {
105         new_receiver->incoming_links = old_receiver->incoming_links;
106         old_receiver->incoming_links.clear();
107         
108         for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
109                 Node *sender = new_receiver->incoming_links[i];
110                 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
111                         if (sender->outgoing_links[j] == old_receiver) {
112                                 sender->outgoing_links[j] = new_receiver;
113                         }
114                 }
115         }       
116 }
117
118 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
119 {
120         new_sender->outgoing_links = old_sender->outgoing_links;
121         old_sender->outgoing_links.clear();
122         
123         for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
124                 Node *receiver = new_sender->outgoing_links[i];
125                 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
126                         if (receiver->incoming_links[j] == old_sender) {
127                                 receiver->incoming_links[j] = new_sender;
128                         }
129                 }
130         }       
131 }
132
133 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
134 {
135         for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
136                 if (sender->outgoing_links[i] == receiver) {
137                         sender->outgoing_links[i] = middle;
138                         middle->incoming_links.push_back(sender);
139                 }
140         }
141         for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
142                 if (receiver->incoming_links[i] == sender) {
143                         receiver->incoming_links[i] = middle;
144                         middle->outgoing_links.push_back(receiver);
145                 }
146         }
147
148         assert(middle->incoming_links.size() == middle->effect->num_inputs());
149 }
150
151 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
152 {
153         assert(node->effect->needs_texture_bounce());
154         assert(input_num < node->incoming_links.size());
155         assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
156         assert(node->incoming_links[input_num]->bound_sampler_num < 8);
157         return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
158 }
159
160 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
161 {
162         if (node->output_gamma_curve == GAMMA_LINEAR &&
163             node->effect->effect_type_id() != "GammaCompressionEffect") {
164                 return;
165         }
166         if (node->effect->num_inputs() == 0) {
167                 nonlinear_inputs->push_back(node);
168         } else {
169                 assert(node->effect->num_inputs() == node->incoming_links.size());
170                 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
171                         find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
172                 }
173         }
174 }
175
176 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
177 {
178         assert(!finalized);
179         assert(inputs.size() == effect->num_inputs());
180         Node *node = add_node(effect);
181         for (unsigned i = 0; i < inputs.size(); ++i) {
182                 assert(node_map.count(inputs[i]) != 0);
183                 connect_nodes(node_map[inputs[i]], node);
184         }
185         return effect;
186 }
187
188 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
189 string replace_prefix(const string &text, const string &prefix)
190 {
191         string output;
192         size_t start = 0;
193
194         while (start < text.size()) {
195                 size_t pos = text.find("PREFIX(", start);
196                 if (pos == string::npos) {
197                         output.append(text.substr(start, string::npos));
198                         break;
199                 }
200
201                 output.append(text.substr(start, pos - start));
202                 output.append(prefix);
203                 output.append("_");
204
205                 pos += strlen("PREFIX(");
206         
207                 // Output stuff until we find the matching ), which we then eat.
208                 int depth = 1;
209                 size_t end_arg_pos = pos;
210                 while (end_arg_pos < text.size()) {
211                         if (text[end_arg_pos] == '(') {
212                                 ++depth;
213                         } else if (text[end_arg_pos] == ')') {
214                                 --depth;
215                                 if (depth == 0) {
216                                         break;
217                                 }
218                         }
219                         ++end_arg_pos;
220                 }
221                 output.append(text.substr(pos, end_arg_pos - pos));
222                 ++end_arg_pos;
223                 assert(depth == 0);
224                 start = end_arg_pos;
225         }
226         return output;
227 }
228
229 void EffectChain::compile_glsl_program(Phase *phase)
230 {
231         string frag_shader = read_version_dependent_file("header", "frag");
232
233         // Create functions for all the texture inputs that we need.
234         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
235                 Node *input = phase->inputs[i]->output_node;
236                 char effect_id[256];
237                 sprintf(effect_id, "in%u", i);
238                 phase->effect_ids.insert(make_pair(input, effect_id));
239         
240                 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
241                 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
242                 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
243                 frag_shader += "}\n";
244                 frag_shader += "\n";
245         }
246
247         for (unsigned i = 0; i < phase->effects.size(); ++i) {
248                 Node *node = phase->effects[i];
249                 char effect_id[256];
250                 sprintf(effect_id, "eff%u", i);
251                 phase->effect_ids.insert(make_pair(node, effect_id));
252
253                 if (node->incoming_links.size() == 1) {
254                         frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
255                 } else {
256                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
257                                 char buf[256];
258                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
259                                 frag_shader += buf;
260                         }
261                 }
262         
263                 frag_shader += "\n";
264                 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
265                 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), effect_id);
266                 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
267                 frag_shader += "#undef PREFIX\n";
268                 frag_shader += "#undef FUNCNAME\n";
269                 if (node->incoming_links.size() == 1) {
270                         frag_shader += "#undef INPUT\n";
271                 } else {
272                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
273                                 char buf[256];
274                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
275                                 frag_shader += buf;
276                         }
277                 }
278                 frag_shader += "\n";
279         }
280         frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
281         frag_shader.append(read_version_dependent_file("footer", "frag"));
282
283         string vert_shader = read_version_dependent_file("vs", "vert");
284         phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, 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         // Output the graph as it is before we do any conversions on it.
1333         output_dot("step0-start.dot");
1334
1335         // Give each effect in turn a chance to rewrite its own part of the graph.
1336         // Note that if more effects are added as part of this, they will be
1337         // picked up as part of the same for loop, since they are added at the end.
1338         for (unsigned i = 0; i < nodes.size(); ++i) {
1339                 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1340         }
1341         output_dot("step1-rewritten.dot");
1342
1343         find_color_spaces_for_inputs();
1344         output_dot("step2-input-colorspace.dot");
1345
1346         propagate_alpha();
1347         output_dot("step3-propagated-alpha.dot");
1348
1349         propagate_gamma_and_color_space();
1350         output_dot("step4-propagated-all.dot");
1351
1352         fix_internal_color_spaces();
1353         fix_internal_alpha(6);
1354         fix_output_color_space();
1355         output_dot("step7-output-colorspacefix.dot");
1356         fix_output_alpha();
1357         output_dot("step8-output-alphafix.dot");
1358
1359         // Note that we need to fix gamma after colorspace conversion,
1360         // because colorspace conversions might create needs for gamma conversions.
1361         // Also, we need to run an extra pass of fix_internal_gamma() after 
1362         // fixing the output gamma, as we only have conversions to/from linear,
1363         // and fix_internal_alpha() since GammaCompressionEffect needs
1364         // postmultiplied input.
1365         fix_internal_gamma_by_asking_inputs(9);
1366         fix_internal_gamma_by_inserting_nodes(10);
1367         fix_output_gamma();
1368         output_dot("step11-output-gammafix.dot");
1369         propagate_alpha();
1370         output_dot("step12-output-alpha-propagated.dot");
1371         fix_internal_alpha(13);
1372         output_dot("step14-output-alpha-fixed.dot");
1373         fix_internal_gamma_by_asking_inputs(15);
1374         fix_internal_gamma_by_inserting_nodes(16);
1375
1376         output_dot("step17-before-dither.dot");
1377
1378         add_dither_if_needed();
1379
1380         output_dot("step18-final.dot");
1381         
1382         // Construct all needed GLSL programs, starting at the output.
1383         // We need to keep track of which effects have already been computed,
1384         // as an effect with multiple users could otherwise be calculated
1385         // multiple times.
1386         map<Node *, Phase *> completed_effects;
1387         construct_phase(find_output_node(), &completed_effects);
1388
1389         output_dot("step19-split-to-phases.dot");
1390
1391         assert(phases[0]->inputs.empty());
1392         
1393         finalized = true;
1394 }
1395
1396 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1397 {
1398         assert(finalized);
1399
1400         // Save original viewport.
1401         GLuint x = 0, y = 0;
1402
1403         if (width == 0 && height == 0) {
1404                 GLint viewport[4];
1405                 glGetIntegerv(GL_VIEWPORT, viewport);
1406                 x = viewport[0];
1407                 y = viewport[1];
1408                 width = viewport[2];
1409                 height = viewport[3];
1410         }
1411
1412         // Basic state.
1413         glDisable(GL_BLEND);
1414         check_error();
1415         glDisable(GL_DEPTH_TEST);
1416         check_error();
1417         glDepthMask(GL_FALSE);
1418         check_error();
1419
1420         set<Phase *> generated_mipmaps;
1421
1422         // We choose the simplest option of having one texture per output,
1423         // since otherwise this turns into an (albeit simple) register allocation problem.
1424         map<Phase *, GLuint> output_textures;
1425
1426         for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1427                 Phase *phase = phases[phase_num];
1428
1429                 if (phase_num == phases.size() - 1) {
1430                         // Last phase goes to the output the user specified.
1431                         glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1432                         check_error();
1433                         GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1434                         assert(status == GL_FRAMEBUFFER_COMPLETE);
1435                         glViewport(x, y, width, height);
1436                         if (dither_effect != NULL) {
1437                                 CHECK(dither_effect->set_int("output_width", width));
1438                                 CHECK(dither_effect->set_int("output_height", height));
1439                         }
1440                 }
1441                 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1442         }
1443
1444         for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1445              texture_it != output_textures.end();
1446              ++texture_it) {
1447                 resource_pool->release_2d_texture(texture_it->second);
1448         }
1449
1450         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1451         check_error();
1452         glUseProgram(0);
1453         check_error();
1454 }
1455
1456 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1457 {
1458         GLuint fbo = 0;
1459
1460         // Find a texture for this phase.
1461         inform_input_sizes(phase);
1462         if (!last_phase) {
1463                 find_output_size(phase);
1464
1465                 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1466                 output_textures->insert(make_pair(phase, tex_num));
1467         }
1468
1469         const GLuint glsl_program_num = phase->glsl_program_num;
1470         check_error();
1471         glUseProgram(glsl_program_num);
1472         check_error();
1473
1474         // Set up RTT inputs for this phase.
1475         for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1476                 glActiveTexture(GL_TEXTURE0 + sampler);
1477                 Phase *input = phase->inputs[sampler];
1478                 input->output_node->bound_sampler_num = sampler;
1479                 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1480                 check_error();
1481                 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1482                         glGenerateMipmap(GL_TEXTURE_2D);
1483                         check_error();
1484                         generated_mipmaps->insert(input);
1485                 }
1486                 setup_rtt_sampler(glsl_program_num, sampler, phase->effect_ids[input->output_node], phase->input_needs_mipmaps);
1487         }
1488
1489         // And now the output. (Already set up for us if it is the last phase.)
1490         if (!last_phase) {
1491                 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1492                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1493                 glViewport(0, 0, phase->output_width, phase->output_height);
1494         }
1495
1496         // Give the required parameters to all the effects.
1497         unsigned sampler_num = phase->inputs.size();
1498         for (unsigned i = 0; i < phase->effects.size(); ++i) {
1499                 Node *node = phase->effects[i];
1500                 unsigned old_sampler_num = sampler_num;
1501                 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1502                 check_error();
1503
1504                 if (node->effect->is_single_texture()) {
1505                         assert(sampler_num - old_sampler_num == 1);
1506                         node->bound_sampler_num = old_sampler_num;
1507                 } else {
1508                         node->bound_sampler_num = -1;
1509                 }
1510         }
1511
1512         // Now draw!
1513         float vertices[] = {
1514                 0.0f, 1.0f,
1515                 0.0f, 0.0f,
1516                 1.0f, 1.0f,
1517                 1.0f, 0.0f
1518         };
1519
1520         GLuint vao;
1521         glGenVertexArrays(1, &vao);
1522         check_error();
1523         glBindVertexArray(vao);
1524         check_error();
1525
1526         GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1527         GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices);  // Same as vertices.
1528
1529         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1530         check_error();
1531
1532         cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1533         cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1534         
1535         glUseProgram(0);
1536         check_error();
1537
1538         for (unsigned i = 0; i < phase->effects.size(); ++i) {
1539                 Node *node = phase->effects[i];
1540                 node->effect->clear_gl_state();
1541         }
1542
1543         if (!last_phase) {
1544                 resource_pool->release_fbo(fbo);
1545         }
1546
1547         glDeleteVertexArrays(1, &vao);
1548         check_error();
1549 }
1550
1551 void EffectChain::setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const string &effect_id, bool use_mipmaps)
1552 {
1553         glActiveTexture(GL_TEXTURE0 + sampler_num);
1554         check_error();
1555         if (use_mipmaps) {
1556                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1557                 check_error();
1558         } else {
1559                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1560                 check_error();
1561         }
1562         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1563         check_error();
1564         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1565         check_error();
1566
1567         string texture_name = string("tex_") + effect_id;
1568         glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler_num);
1569         check_error();
1570 }
1571
1572 }  // namespace movit