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