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