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