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