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