]> git.sesse.net Git - movit/blob - effect_chain.cpp
Add an unsharp mask effect, to complement the more expensive deconvolution sharpening.
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <stdio.h>
4 #include <math.h>
5 #include <string.h>
6 #include <assert.h>
7
8 #include <algorithm>
9 #include <set>
10 #include <stack>
11 #include <vector>
12
13 #include "util.h"
14 #include "effect_chain.h"
15 #include "gamma_expansion_effect.h"
16 #include "gamma_compression_effect.h"
17 #include "colorspace_conversion_effect.h"
18 #include "input.h"
19 #include "opengl.h"
20
21 EffectChain::EffectChain(float aspect_nom, float aspect_denom)
22         : aspect_nom(aspect_nom),
23           aspect_denom(aspect_denom),
24           finalized(false) {}
25
26 Input *EffectChain::add_input(Input *input)
27 {
28         inputs.push_back(input);
29
30         Node *node = add_node(input);
31         node->output_color_space = input->get_color_space();
32         node->output_gamma_curve = input->get_gamma_curve();
33         return input;
34 }
35
36 void EffectChain::add_output(const ImageFormat &format)
37 {
38         output_format = format;
39 }
40
41 Node *EffectChain::add_node(Effect *effect)
42 {
43         char effect_id[256];
44         sprintf(effect_id, "eff%u", (unsigned)nodes.size());
45
46         Node *node = new Node;
47         node->effect = effect;
48         node->disabled = false;
49         node->effect_id = effect_id;
50         node->output_color_space = COLORSPACE_INVALID;
51         node->output_gamma_curve = GAMMA_INVALID;
52
53         nodes.push_back(node);
54         node_map[effect] = node;
55         return node;
56 }
57
58 void EffectChain::connect_nodes(Node *sender, Node *receiver)
59 {
60         sender->outgoing_links.push_back(receiver);
61         receiver->incoming_links.push_back(sender);
62 }
63
64 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
65 {
66         new_receiver->incoming_links = old_receiver->incoming_links;
67         old_receiver->incoming_links.clear();
68         
69         for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
70                 Node *sender = new_receiver->incoming_links[i];
71                 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
72                         if (sender->outgoing_links[j] == old_receiver) {
73                                 sender->outgoing_links[j] = new_receiver;
74                         }
75                 }
76         }       
77 }
78
79 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
80 {
81         new_sender->outgoing_links = old_sender->outgoing_links;
82         old_sender->outgoing_links.clear();
83         
84         for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
85                 Node *receiver = new_sender->outgoing_links[i];
86                 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
87                         if (receiver->incoming_links[j] == old_sender) {
88                                 receiver->incoming_links[j] = new_sender;
89                         }
90                 }
91         }       
92 }
93
94 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
95 {
96         for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
97                 if (sender->outgoing_links[i] == receiver) {
98                         sender->outgoing_links[i] = middle;
99                         middle->incoming_links.push_back(sender);
100                 }
101         }
102         for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
103                 if (receiver->incoming_links[i] == sender) {
104                         receiver->incoming_links[i] = middle;
105                         middle->outgoing_links.push_back(receiver);
106                 }
107         }
108
109         assert(middle->incoming_links.size() == middle->effect->num_inputs());
110 }
111
112 void EffectChain::find_all_nonlinear_inputs(Node *node, std::vector<Node *> *nonlinear_inputs)
113 {
114         if (node->output_gamma_curve == GAMMA_LINEAR) {
115                 return;
116         }
117         if (node->effect->num_inputs() == 0) {
118                 nonlinear_inputs->push_back(node);
119         } else {
120                 assert(node->effect->num_inputs() == node->incoming_links.size());
121                 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
122                         find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
123                 }
124         }
125 }
126
127 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
128 {
129         assert(inputs.size() == effect->num_inputs());
130         Node *node = add_node(effect);
131         for (unsigned i = 0; i < inputs.size(); ++i) {
132                 assert(node_map.count(inputs[i]) != 0);
133                 connect_nodes(node_map[inputs[i]], node);
134         }
135         return effect;
136 }
137
138 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
139 std::string replace_prefix(const std::string &text, const std::string &prefix)
140 {
141         std::string output;
142         size_t start = 0;
143
144         while (start < text.size()) {
145                 size_t pos = text.find("PREFIX(", start);
146                 if (pos == std::string::npos) {
147                         output.append(text.substr(start, std::string::npos));
148                         break;
149                 }
150
151                 output.append(text.substr(start, pos - start));
152                 output.append(prefix);
153                 output.append("_");
154
155                 pos += strlen("PREFIX(");
156         
157                 // Output stuff until we find the matching ), which we then eat.
158                 int depth = 1;
159                 size_t end_arg_pos = pos;
160                 while (end_arg_pos < text.size()) {
161                         if (text[end_arg_pos] == '(') {
162                                 ++depth;
163                         } else if (text[end_arg_pos] == ')') {
164                                 --depth;
165                                 if (depth == 0) {
166                                         break;
167                                 }
168                         }
169                         ++end_arg_pos;
170                 }
171                 output.append(text.substr(pos, end_arg_pos - pos));
172                 ++end_arg_pos;
173                 assert(depth == 0);
174                 start = end_arg_pos;
175         }
176         return output;
177 }
178
179 Phase *EffectChain::compile_glsl_program(
180         const std::vector<Node *> &inputs,
181         const std::vector<Node *> &effects)
182 {
183         assert(!effects.empty());
184
185         // Deduplicate the inputs.
186         std::vector<Node *> true_inputs = inputs;
187         std::sort(true_inputs.begin(), true_inputs.end());
188         true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
189
190         bool input_needs_mipmaps = false;
191         std::string frag_shader = read_file("header.frag");
192
193         // Create functions for all the texture inputs that we need.
194         for (unsigned i = 0; i < true_inputs.size(); ++i) {
195                 Node *input = true_inputs[i];
196         
197                 frag_shader += std::string("uniform sampler2D tex_") + input->effect_id + ";\n";
198                 frag_shader += std::string("vec4 ") + input->effect_id + "(vec2 tc) {\n";
199                 frag_shader += "\treturn texture2D(tex_" + input->effect_id + ", tc);\n";
200                 frag_shader += "}\n";
201                 frag_shader += "\n";
202         }
203
204         for (unsigned i = 0; i < effects.size(); ++i) {
205                 Node *node = effects[i];
206
207                 if (node->incoming_links.size() == 1) {
208                         frag_shader += std::string("#define INPUT ") + node->incoming_links[0]->effect_id + "\n";
209                 } else {
210                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
211                                 char buf[256];
212                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, node->incoming_links[j]->effect_id.c_str());
213                                 frag_shader += buf;
214                         }
215                 }
216         
217                 frag_shader += "\n";
218                 frag_shader += std::string("#define FUNCNAME ") + node->effect_id + "\n";
219                 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), node->effect_id);
220                 frag_shader += replace_prefix(node->effect->output_fragment_shader(), node->effect_id);
221                 frag_shader += "#undef PREFIX\n";
222                 frag_shader += "#undef FUNCNAME\n";
223                 if (node->incoming_links.size() == 1) {
224                         frag_shader += "#undef INPUT\n";
225                 } else {
226                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
227                                 char buf[256];
228                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
229                                 frag_shader += buf;
230                         }
231                 }
232                 frag_shader += "\n";
233
234                 input_needs_mipmaps |= node->effect->needs_mipmaps();
235         }
236         for (unsigned i = 0; i < effects.size(); ++i) {
237                 Node *node = effects[i];
238                 if (node->effect->num_inputs() == 0) {
239                         node->effect->set_int("needs_mipmaps", input_needs_mipmaps);
240                 }
241         }
242         frag_shader += std::string("#define INPUT ") + effects.back()->effect_id + "\n";
243         frag_shader.append(read_file("footer.frag"));
244         printf("%s\n", frag_shader.c_str());
245         
246         GLuint glsl_program_num = glCreateProgram();
247         GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
248         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
249         glAttachShader(glsl_program_num, vs_obj);
250         check_error();
251         glAttachShader(glsl_program_num, fs_obj);
252         check_error();
253         glLinkProgram(glsl_program_num);
254         check_error();
255
256         Phase *phase = new Phase;
257         phase->glsl_program_num = glsl_program_num;
258         phase->input_needs_mipmaps = input_needs_mipmaps;
259         phase->inputs = true_inputs;
260         phase->effects = effects;
261
262         return phase;
263 }
264
265 // Construct GLSL programs, starting at the given effect and following
266 // the chain from there. We end a program every time we come to an effect
267 // marked as "needs texture bounce", one that is used by multiple other
268 // effects, every time an effect wants to change the output size,
269 // and of course at the end.
270 //
271 // We follow a quite simple depth-first search from the output, although
272 // without any explicit recursion.
273 void EffectChain::construct_glsl_programs(Node *output)
274 {
275         // Which effects have already been completed in this phase?
276         // We need to keep track of it, as an effect with multiple outputs
277         // could otherwise be calculate multiple times.
278         std::set<Node *> completed_effects;
279
280         // Effects in the current phase, as well as inputs (outputs from other phases
281         // that we depend on). Note that since we start iterating from the end,
282         // the effect list will be in the reverse order.
283         std::vector<Node *> this_phase_inputs;
284         std::vector<Node *> this_phase_effects;
285
286         // Effects that we have yet to calculate, but that we know should
287         // be in the current phase.
288         std::stack<Node *> effects_todo_this_phase;
289
290         // Effects that we have yet to calculate, but that come from other phases.
291         // We delay these until we have this phase done in its entirety,
292         // at which point we pick any of them and start a new phase from that.
293         std::stack<Node *> effects_todo_other_phases;
294
295         effects_todo_this_phase.push(output);
296
297         for ( ;; ) {  // Termination condition within loop.
298                 if (!effects_todo_this_phase.empty()) {
299                         // OK, we have more to do this phase.
300                         Node *node = effects_todo_this_phase.top();
301                         effects_todo_this_phase.pop();
302
303                         // This should currently only happen for effects that are phase outputs,
304                         // and we throw those out separately below.
305                         assert(completed_effects.count(node) == 0);
306
307                         this_phase_effects.push_back(node);
308                         completed_effects.insert(node);
309
310                         // Find all the dependencies of this effect, and add them to the stack.
311                         std::vector<Node *> deps = node->incoming_links;
312                         assert(node->effect->num_inputs() == deps.size());
313                         for (unsigned i = 0; i < deps.size(); ++i) {
314                                 bool start_new_phase = false;
315
316                                 // FIXME: If we sample directly from a texture, we won't need this.
317                                 if (node->effect->needs_texture_bounce()) {
318                                         start_new_phase = true;
319                                 }
320
321                                 if (deps[i]->outgoing_links.size() > 1 && deps[i]->effect->num_inputs() > 0) {
322                                         // More than one effect uses this as the input,
323                                         // and it is not a texture itself.
324                                         // The easiest thing to do (and probably also the safest
325                                         // performance-wise in most cases) is to bounce it to a texture
326                                         // and then let the next passes read from that.
327                                         start_new_phase = true;
328                                 }
329
330                                 if (deps[i]->effect->changes_output_size()) {
331                                         start_new_phase = true;
332                                 }
333
334                                 if (start_new_phase) {
335                                         effects_todo_other_phases.push(deps[i]);
336                                         this_phase_inputs.push_back(deps[i]);
337                                 } else {
338                                         effects_todo_this_phase.push(deps[i]);
339                                 }
340                         }
341                         continue;
342                 }
343
344                 // No more effects to do this phase. Take all the ones we have,
345                 // and create a GLSL program for it.
346                 if (!this_phase_effects.empty()) {
347                         reverse(this_phase_effects.begin(), this_phase_effects.end());
348                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
349                         this_phase_effects.back()->phase = phases.back();
350                         this_phase_inputs.clear();
351                         this_phase_effects.clear();
352                 }
353                 assert(this_phase_inputs.empty());
354                 assert(this_phase_effects.empty());
355
356                 // If we have no effects left, exit.
357                 if (effects_todo_other_phases.empty()) {
358                         break;
359                 }
360
361                 Node *node = effects_todo_other_phases.top();
362                 effects_todo_other_phases.pop();
363
364                 if (completed_effects.count(node) == 0) {
365                         // Start a new phase, calculating from this effect.
366                         effects_todo_this_phase.push(node);
367                 }
368         }
369
370         // Finally, since the phases are found from the output but must be executed
371         // from the input(s), reverse them, too.
372         std::reverse(phases.begin(), phases.end());
373 }
374
375 void EffectChain::output_dot(const char *filename)
376 {
377         FILE *fp = fopen(filename, "w");
378         if (fp == NULL) {
379                 perror(filename);
380                 exit(1);
381         }
382
383         fprintf(fp, "digraph G {\n");
384         for (unsigned i = 0; i < nodes.size(); ++i) {
385                 fprintf(fp, "  n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
386                 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
387                         std::vector<std::string> labels;
388
389                         if (nodes[i]->outgoing_links[j]->effect->needs_texture_bounce()) {
390                                 labels.push_back("needs_bounce");
391                         }
392                         if (nodes[i]->effect->changes_output_size()) {
393                                 labels.push_back("resize");
394                         }
395
396                         switch (nodes[i]->output_color_space) {
397                         case COLORSPACE_INVALID:
398                                 labels.push_back("spc[invalid]");
399                                 break;
400                         case COLORSPACE_REC_601_525:
401                                 labels.push_back("spc[rec601-525]");
402                                 break;
403                         case COLORSPACE_REC_601_625:
404                                 labels.push_back("spc[rec601-625]");
405                                 break;
406                         default:
407                                 break;
408                         }
409
410                         switch (nodes[i]->output_gamma_curve) {
411                         case GAMMA_INVALID:
412                                 labels.push_back("gamma[invalid]");
413                                 break;
414                         case GAMMA_sRGB:
415                                 labels.push_back("gamma[sRGB]");
416                                 break;
417                         case GAMMA_REC_601:  // and GAMMA_REC_709
418                                 labels.push_back("gamma[rec601/709]");
419                                 break;
420                         default:
421                                 break;
422                         }
423
424                         if (labels.empty()) {
425                                 fprintf(fp, "  n%ld -> n%ld;\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j]);
426                         } else {
427                                 std::string label = labels[0];
428                                 for (unsigned k = 1; k < labels.size(); ++k) {
429                                         label += ", " + labels[k];
430                                 }
431                                 fprintf(fp, "  n%ld -> n%ld [label=\"%s\"];\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j], label.c_str());
432                         }
433                 }
434         }
435         fprintf(fp, "}\n");
436
437         fclose(fp);
438 }
439
440 unsigned EffectChain::fit_rectangle_to_aspect(unsigned width, unsigned height)
441 {
442         if (float(width) * aspect_denom >= float(height) * aspect_nom) {
443                 // Same aspect, or W/H > aspect (image is wider than the frame).
444                 // In either case, keep width.
445                 return width;
446         } else {
447                 // W/H < aspect (image is taller than the frame), so keep height,
448                 // and adjust width correspondingly.
449                 return lrintf(height * aspect_nom / aspect_denom);
450         }
451 }
452
453 // Propagate input texture sizes throughout, and inform effects downstream.
454 // (Like a lot of other code, we depend on effects being in topological order.)
455 void EffectChain::inform_input_sizes(Phase *phase)
456 {
457         // All effects that have a defined size (inputs and RTT inputs)
458         // get that. Reset all others.
459         for (unsigned i = 0; i < phase->effects.size(); ++i) {
460                 Node *node = phase->effects[i];
461                 if (node->effect->num_inputs() == 0) {
462                         Input *input = static_cast<Input *>(node->effect);
463                         node->output_width = input->get_width();
464                         node->output_height = input->get_height();
465                         assert(node->output_width != 0);
466                         assert(node->output_height != 0);
467                 } else {
468                         node->output_width = node->output_height = 0;
469                 }
470         }
471         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
472                 Node *input = phase->inputs[i];
473                 input->output_width = input->phase->output_width;
474                 input->output_height = input->phase->output_height;
475                 assert(input->output_width != 0);
476                 assert(input->output_height != 0);
477         }
478
479         // Now propagate from the inputs towards the end, and inform as we go.
480         // The rules are simple:
481         //
482         //   1. Don't touch effects that already have given sizes (ie., inputs).
483         //   2. If all of your inputs have the same size, that will be your output size.
484         //   3. Otherwise, your output size is 0x0.
485         for (unsigned i = 0; i < phase->effects.size(); ++i) {
486                 Node *node = phase->effects[i];
487                 if (node->effect->num_inputs() == 0) {
488                         continue;
489                 }
490                 unsigned this_output_width = 0;
491                 unsigned this_output_height = 0;
492                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
493                         Node *input = node->incoming_links[j];
494                         node->effect->inform_input_size(j, input->output_width, input->output_height);
495                         if (j == 0) {
496                                 this_output_width = input->output_width;
497                                 this_output_height = input->output_height;
498                         } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
499                                 // Inputs disagree.
500                                 this_output_width = 0;
501                                 this_output_height = 0;
502                         }
503                 }
504                 node->output_width = this_output_width;
505                 node->output_height = this_output_height;
506         }
507 }
508
509 // Note: You should call inform_input_sizes() before this, as the last effect's
510 // desired output size might change based on the inputs.
511 void EffectChain::find_output_size(Phase *phase)
512 {
513         Node *output_node = phase->effects.back();
514
515         // If the last effect explicitly sets an output size, use that.
516         if (output_node->effect->changes_output_size()) {
517                 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
518                 return;
519         }
520
521         // If not, look at the input phases and textures.
522         // We select the largest one (by fit into the current aspect).
523         unsigned best_width = 0;
524         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
525                 Node *input = phase->inputs[i];
526                 assert(input->phase->output_width != 0);
527                 assert(input->phase->output_height != 0);
528                 unsigned width = fit_rectangle_to_aspect(input->phase->output_width, input->phase->output_height);
529                 if (width > best_width) {
530                         best_width = width;
531                 }
532         }
533         for (unsigned i = 0; i < phase->effects.size(); ++i) {
534                 Effect *effect = phase->effects[i]->effect;
535                 if (effect->num_inputs() != 0) {
536                         continue;
537                 }
538
539                 Input *input = static_cast<Input *>(effect);
540                 unsigned width = fit_rectangle_to_aspect(input->get_width(), input->get_height());
541                 if (width > best_width) {
542                         best_width = width;
543                 }
544         }
545         assert(best_width != 0);
546         phase->output_width = best_width;
547         phase->output_height = best_width * aspect_denom / aspect_nom;
548 }
549
550 void EffectChain::sort_nodes_topologically()
551 {
552         std::set<Node *> visited_nodes;
553         std::vector<Node *> sorted_list;
554         for (unsigned i = 0; i < nodes.size(); ++i) {
555                 if (nodes[i]->incoming_links.size() == 0) {
556                         topological_sort_visit_node(nodes[i], &visited_nodes, &sorted_list);
557                 }
558         }
559         reverse(sorted_list.begin(), sorted_list.end());
560         nodes = sorted_list;
561 }
562
563 void EffectChain::topological_sort_visit_node(Node *node, std::set<Node *> *visited_nodes, std::vector<Node *> *sorted_list)
564 {
565         if (visited_nodes->count(node) != 0) {
566                 return;
567         }
568         visited_nodes->insert(node);
569         for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
570                 topological_sort_visit_node(node->outgoing_links[i], visited_nodes, sorted_list);
571         }
572         sorted_list->push_back(node);
573 }
574
575 // Propagate gamma and color space information as far as we can in the graph.
576 // The rules are simple: Anything where all the inputs agree, get that as
577 // output as well. Anything else keeps having *_INVALID.
578 void EffectChain::propagate_gamma_and_color_space()
579 {
580         // We depend on going through the nodes in order.
581         sort_nodes_topologically();
582
583         for (unsigned i = 0; i < nodes.size(); ++i) {
584                 Node *node = nodes[i];
585                 if (node->disabled) {
586                         continue;
587                 }
588                 assert(node->incoming_links.size() == node->effect->num_inputs());
589                 if (node->incoming_links.size() == 0) {
590                         assert(node->output_color_space != COLORSPACE_INVALID);
591                         assert(node->output_gamma_curve != GAMMA_INVALID);
592                         continue;
593                 }
594
595                 ColorSpace color_space = node->incoming_links[0]->output_color_space;
596                 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
597                 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
598                         if (node->incoming_links[j]->output_color_space != color_space) {
599                                 color_space = COLORSPACE_INVALID;
600                         }
601                         if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
602                                 gamma_curve = GAMMA_INVALID;
603                         }
604                 }
605
606                 // The conversion effects already have their outputs set correctly,
607                 // so leave them alone.
608                 if (node->effect->effect_type_id() != "ColorSpaceConversionEffect") {
609                         node->output_color_space = color_space;
610                 }               
611                 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
612                     node->effect->effect_type_id() != "GammaExpansionEffect") {
613                         node->output_gamma_curve = gamma_curve;
614                 }               
615         }
616 }
617
618 bool EffectChain::node_needs_colorspace_fix(Node *node)
619 {
620         if (node->disabled) {
621                 return false;
622         }
623         if (node->effect->num_inputs() == 0) {
624                 return false;
625         }
626
627         // propagate_gamma_and_color_space() has already set our output
628         // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
629         if (node->output_color_space == COLORSPACE_INVALID) {
630                 return true;
631         }
632         return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
633 }
634
635 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
636 // the graph. Our strategy is not always optimal, but quite simple:
637 // Find an effect that's as early as possible where the inputs are of
638 // unacceptable colorspaces (that is, either different, or, if the effect only
639 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
640 // propagate the information anew, and repeat until there are no more such
641 // effects.
642 void EffectChain::fix_internal_color_spaces()
643 {
644         unsigned colorspace_propagation_pass = 0;
645         bool found_any;
646         do {
647                 found_any = false;
648                 for (unsigned i = 0; i < nodes.size(); ++i) {
649                         Node *node = nodes[i];
650                         if (!node_needs_colorspace_fix(node)) {
651                                 continue;
652                         }
653
654                         // Go through each input that is not sRGB, and insert
655                         // a colorspace conversion before it.
656                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
657                                 Node *input = node->incoming_links[j];
658                                 assert(input->output_color_space != COLORSPACE_INVALID);
659                                 if (input->output_color_space == COLORSPACE_sRGB) {
660                                         continue;
661                                 }
662                                 Node *conversion = add_node(new ColorSpaceConversionEffect());
663                                 conversion->effect->set_int("source_space", input->output_color_space);
664                                 conversion->effect->set_int("destination_space", COLORSPACE_sRGB);
665                                 conversion->output_color_space = COLORSPACE_sRGB;
666                                 insert_node_between(input, conversion, node);
667                         }
668
669                         // Re-sort topologically, and propagate the new information.
670                         propagate_gamma_and_color_space();
671                         
672                         found_any = true;
673                         break;
674                 }
675         
676                 char filename[256];
677                 sprintf(filename, "step3-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
678                 output_dot(filename);
679                 assert(colorspace_propagation_pass < 100);
680         } while (found_any);
681
682         for (unsigned i = 0; i < nodes.size(); ++i) {
683                 Node *node = nodes[i];
684                 if (node->disabled) {
685                         continue;
686                 }
687                 assert(node->output_color_space != COLORSPACE_INVALID);
688         }
689 }
690
691 // Make so that the output is in the desired color space.
692 void EffectChain::fix_output_color_space()
693 {
694         Node *output = find_output_node();
695         if (output->output_color_space != output_format.color_space) {
696                 Node *conversion = add_node(new ColorSpaceConversionEffect());
697                 conversion->effect->set_int("source_space", output->output_color_space);
698                 conversion->effect->set_int("destination_space", output_format.color_space);
699                 conversion->output_color_space = output_format.color_space;
700                 connect_nodes(output, conversion);
701         }
702 }
703
704 bool EffectChain::node_needs_gamma_fix(Node *node)
705 {
706         if (node->disabled) {
707                 return false;
708         }
709         if (node->effect->num_inputs() == 0) {
710                 return false;
711         }
712
713         // propagate_gamma_and_color_space() has already set our output
714         // to GAMMA_INVALID if the inputs differ, so we can rely on that,
715         // except for GammaCompressionEffect.
716         if (node->output_gamma_curve == GAMMA_INVALID) {
717                 return true;
718         }
719         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
720                 assert(node->incoming_links.size() == 1);
721                 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
722         }
723         return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
724 }
725
726 // Very similar to fix_internal_color_spaces(), but for gamma.
727 // There is one difference, though; before we start adding conversion nodes,
728 // we see if we can get anything out of asking the sources to deliver
729 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
730 // does that part, while fix_internal_gamma_by_inserting_nodes()
731 // inserts nodes as needed afterwards.
732 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
733 {
734         unsigned gamma_propagation_pass = 0;
735         bool found_any;
736         do {
737                 found_any = false;
738                 for (unsigned i = 0; i < nodes.size(); ++i) {
739                         Node *node = nodes[i];
740                         if (!node_needs_gamma_fix(node)) {
741                                 continue;
742                         }
743
744                         // See if all inputs can give us linear gamma. If not, leave it.
745                         std::vector<Node *> nonlinear_inputs;
746                         find_all_nonlinear_inputs(node, &nonlinear_inputs);
747
748                         bool all_ok = true;
749                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
750                                 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
751                                 all_ok &= input->can_output_linear_gamma();
752                         }
753
754                         if (!all_ok) {
755                                 continue;
756                         }
757
758                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
759                                 nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1);
760                                 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
761                         }
762
763                         // Re-sort topologically, and propagate the new information.
764                         propagate_gamma_and_color_space();
765                         
766                         found_any = true;
767                         break;
768                 }
769         
770                 char filename[256];
771                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
772                 output_dot(filename);
773                 assert(gamma_propagation_pass < 100);
774         } while (found_any);
775 }
776
777 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
778 {
779         unsigned gamma_propagation_pass = 0;
780         bool found_any;
781         do {
782                 found_any = false;
783                 for (unsigned i = 0; i < nodes.size(); ++i) {
784                         Node *node = nodes[i];
785                         if (!node_needs_gamma_fix(node)) {
786                                 continue;
787                         }
788
789                         // Go through each input that is not linear gamma, and insert
790                         // a gamma conversion before it.
791                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
792                                 Node *input = node->incoming_links[j];
793                                 assert(input->output_gamma_curve != GAMMA_INVALID);
794                                 if (input->output_gamma_curve == GAMMA_LINEAR) {
795                                         continue;
796                                 }
797                                 Node *conversion = add_node(new GammaExpansionEffect());
798                                 conversion->effect->set_int("destination_curve", GAMMA_LINEAR);
799                                 conversion->output_gamma_curve = GAMMA_LINEAR;
800                                 insert_node_between(input, conversion, node);
801                         }
802
803                         // Re-sort topologically, and propagate the new information.
804                         propagate_gamma_and_color_space();
805                         
806                         found_any = true;
807                         break;
808                 }
809         
810                 char filename[256];
811                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
812                 output_dot(filename);
813                 assert(gamma_propagation_pass < 100);
814         } while (found_any);
815
816         for (unsigned i = 0; i < nodes.size(); ++i) {
817                 Node *node = nodes[i];
818                 if (node->disabled) {
819                         continue;
820                 }
821                 assert(node->output_gamma_curve != GAMMA_INVALID);
822         }
823 }
824
825 // Make so that the output is in the desired gamma.
826 // Note that this assumes linear input gamma, so it might create the need
827 // for another pass of fix_internal_gamma().
828 void EffectChain::fix_output_gamma()
829 {
830         Node *output = find_output_node();
831         if (output->output_gamma_curve != output_format.gamma_curve) {
832                 Node *conversion = add_node(new GammaCompressionEffect());
833                 conversion->effect->set_int("destination_curve", output_format.gamma_curve);
834                 conversion->output_gamma_curve = output_format.gamma_curve;
835                 connect_nodes(output, conversion);
836         }
837 }
838
839 // Find the output node. This is, simply, one that has no outgoing links.
840 // If there are multiple ones, the graph is malformed (we do not support
841 // multiple outputs right now).
842 Node *EffectChain::find_output_node()
843 {
844         std::vector<Node *> output_nodes;
845         for (unsigned i = 0; i < nodes.size(); ++i) {
846                 Node *node = nodes[i];
847                 if (node->disabled) {
848                         continue;
849                 }
850                 if (node->outgoing_links.empty()) {
851                         output_nodes.push_back(node);
852                 }
853         }
854         assert(output_nodes.size() == 1);
855         return output_nodes[0];
856 }
857
858 void EffectChain::finalize()
859 {
860         // Output the graph as it is before we do any conversions on it.
861         output_dot("step0-start.dot");
862
863         // Give each effect in turn a chance to rewrite its own part of the graph.
864         // Note that if more effects are added as part of this, they will be
865         // picked up as part of the same for loop, since they are added at the end.
866         for (unsigned i = 0; i < nodes.size(); ++i) {
867                 nodes[i]->effect->rewrite_graph(this, nodes[i]);
868         }
869         output_dot("step1-rewritten.dot");
870
871         propagate_gamma_and_color_space();
872         output_dot("step2-propagated.dot");
873
874         fix_internal_color_spaces();
875         fix_output_color_space();
876         output_dot("step4-output-colorspacefix.dot");
877
878         // Note that we need to fix gamma after colorspace conversion,
879         // because colorspace conversions might create needs for gamma conversions.
880         // Also, we need to run an extra pass of fix_internal_gamma() after 
881         // fixing the output gamma, as we only have conversions to/from linear.
882         fix_internal_gamma_by_asking_inputs(5);
883         fix_internal_gamma_by_inserting_nodes(6);
884         fix_output_gamma();
885         output_dot("step8-output-gammafix.dot");
886         fix_internal_gamma_by_asking_inputs(9);
887         fix_internal_gamma_by_inserting_nodes(10);
888
889         output_dot("step11-final.dot");
890         
891         // Construct all needed GLSL programs, starting at the output.
892         construct_glsl_programs(find_output_node());
893
894         // If we have more than one phase, we need intermediate render-to-texture.
895         // Construct an FBO, and then as many textures as we need.
896         // We choose the simplest option of having one texture per output,
897         // since otherwise this turns into an (albeit simple)
898         // register allocation problem.
899         if (phases.size() > 1) {
900                 glGenFramebuffers(1, &fbo);
901
902                 for (unsigned i = 0; i < phases.size() - 1; ++i) {
903                         inform_input_sizes(phases[i]);
904                         find_output_size(phases[i]);
905
906                         Node *output_node = phases[i]->effects.back();
907                         glGenTextures(1, &output_node->output_texture);
908                         check_error();
909                         glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
910                         check_error();
911                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
912                         check_error();
913                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
914                         check_error();
915                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
916                         check_error();
917
918                         output_node->output_texture_width = phases[i]->output_width;
919                         output_node->output_texture_height = phases[i]->output_height;
920                 }
921                 inform_input_sizes(phases.back());
922         }
923                 
924         for (unsigned i = 0; i < inputs.size(); ++i) {
925                 inputs[i]->finalize();
926         }
927
928         assert(phases[0]->inputs.empty());
929         
930         finalized = true;
931 }
932
933 void EffectChain::render_to_screen()
934 {
935         assert(finalized);
936
937         // Save original viewport.
938         GLint viewport[4];
939         glGetIntegerv(GL_VIEWPORT, viewport);
940
941         // Basic state.
942         glDisable(GL_BLEND);
943         check_error();
944         glDisable(GL_DEPTH_TEST);
945         check_error();
946         glDepthMask(GL_FALSE);
947         check_error();
948
949         glMatrixMode(GL_PROJECTION);
950         glLoadIdentity();
951         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
952
953         glMatrixMode(GL_MODELVIEW);
954         glLoadIdentity();
955
956         if (phases.size() > 1) {
957                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
958                 check_error();
959         }
960
961         std::set<Node *> generated_mipmaps;
962
963         for (unsigned phase = 0; phase < phases.size(); ++phase) {
964                 // See if the requested output size has changed. If so, we need to recreate
965                 // the texture (and before we start setting up inputs).
966                 inform_input_sizes(phases[phase]);
967                 if (phase != phases.size() - 1) {
968                         find_output_size(phases[phase]);
969
970                         Node *output_node = phases[phase]->effects.back();
971
972                         if (output_node->output_texture_width != phases[phase]->output_width ||
973                             output_node->output_texture_height != phases[phase]->output_height) {
974                                 glActiveTexture(GL_TEXTURE0);
975                                 check_error();
976                                 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
977                                 check_error();
978                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
979                                 check_error();
980                                 glBindTexture(GL_TEXTURE_2D, 0);
981                                 check_error();
982
983                                 output_node->output_texture_width = phases[phase]->output_width;
984                                 output_node->output_texture_height = phases[phase]->output_height;
985                         }
986                 }
987
988                 glUseProgram(phases[phase]->glsl_program_num);
989                 check_error();
990
991                 // Set up RTT inputs for this phase.
992                 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
993                         glActiveTexture(GL_TEXTURE0 + sampler);
994                         Node *input = phases[phase]->inputs[sampler];
995                         glBindTexture(GL_TEXTURE_2D, input->output_texture);
996                         check_error();
997                         if (phases[phase]->input_needs_mipmaps) {
998                                 if (generated_mipmaps.count(input) == 0) {
999                                         glGenerateMipmap(GL_TEXTURE_2D);
1000                                         check_error();
1001                                         generated_mipmaps.insert(input);
1002                                 }
1003                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1004                                 check_error();
1005                         } else {
1006                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1007                                 check_error();
1008                         }
1009
1010                         std::string texture_name = std::string("tex_") + input->effect_id;
1011                         glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
1012                         check_error();
1013                 }
1014
1015                 // And now the output.
1016                 if (phase == phases.size() - 1) {
1017                         // Last phase goes directly to the screen.
1018                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1019                         check_error();
1020                         glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
1021                 } else {
1022                         Node *output_node = phases[phase]->effects.back();
1023                         glFramebufferTexture2D(
1024                                 GL_FRAMEBUFFER,
1025                                 GL_COLOR_ATTACHMENT0,
1026                                 GL_TEXTURE_2D,
1027                                 output_node->output_texture,
1028                                 0);
1029                         check_error();
1030                         glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
1031                 }
1032
1033                 // Give the required parameters to all the effects.
1034                 unsigned sampler_num = phases[phase]->inputs.size();
1035                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1036                         Node *node = phases[phase]->effects[i];
1037                         node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
1038                         check_error();
1039                 }
1040
1041                 // Now draw!
1042                 glBegin(GL_QUADS);
1043
1044                 glTexCoord2f(0.0f, 0.0f);
1045                 glVertex2f(0.0f, 0.0f);
1046
1047                 glTexCoord2f(1.0f, 0.0f);
1048                 glVertex2f(1.0f, 0.0f);
1049
1050                 glTexCoord2f(1.0f, 1.0f);
1051                 glVertex2f(1.0f, 1.0f);
1052
1053                 glTexCoord2f(0.0f, 1.0f);
1054                 glVertex2f(0.0f, 1.0f);
1055
1056                 glEnd();
1057                 check_error();
1058
1059                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1060                         Node *node = phases[phase]->effects[i];
1061                         node->effect->clear_gl_state();
1062                 }
1063         }
1064 }