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