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