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