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