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