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