22ba189013d0961dcd00f10212a3abca6309875e
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <GL/glew.h>
4 #include <assert.h>
5 #include <locale.h>
6 #include <math.h>
7 #include <stddef.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <algorithm>
12 #include <set>
13 #include <stack>
14 #include <utility>
15 #include <vector>
16
17 #include "alpha_division_effect.h"
18 #include "alpha_multiplication_effect.h"
19 #include "colorspace_conversion_effect.h"
20 #include "dither_effect.h"
21 #include "effect.h"
22 #include "effect_chain.h"
23 #include "gamma_compression_effect.h"
24 #include "gamma_expansion_effect.h"
25 #include "init.h"
26 #include "input.h"
27 #include "resource_pool.h"
28 #include "util.h"
29
30 using namespace std;
31
32 namespace movit {
33
34 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
35         : aspect_nom(aspect_nom),
36           aspect_denom(aspect_denom),
37           dither_effect(NULL),
38           num_dither_bits(0),
39           finalized(false),
40           resource_pool(resource_pool) {
41         if (resource_pool == NULL) {
42                 this->resource_pool = new ResourcePool();
43                 owns_resource_pool = true;
44         } else {
45                 owns_resource_pool = false;
46         }
47 }
48
49 EffectChain::~EffectChain()
50 {
51         for (unsigned i = 0; i < nodes.size(); ++i) {
52                 delete nodes[i]->effect;
53                 delete nodes[i];
54         }
55         for (unsigned i = 0; i < phases.size(); ++i) {
56                 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
57                 delete phases[i];
58         }
59         if (owns_resource_pool) {
60                 delete resource_pool;
61         }
62 }
63
64 Input *EffectChain::add_input(Input *input)
65 {
66         assert(!finalized);
67         inputs.push_back(input);
68         add_node(input);
69         return input;
70 }
71
72 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
73 {
74         assert(!finalized);
75         output_format = format;
76         output_alpha_format = alpha_format;
77 }
78
79 Node *EffectChain::add_node(Effect *effect)
80 {
81         for (unsigned i = 0; i < nodes.size(); ++i) {
82                 assert(nodes[i]->effect != effect);
83         }
84
85         Node *node = new Node;
86         node->effect = effect;
87         node->disabled = false;
88         node->output_color_space = COLORSPACE_INVALID;
89         node->output_gamma_curve = GAMMA_INVALID;
90         node->output_alpha_type = ALPHA_INVALID;
91
92         nodes.push_back(node);
93         node_map[effect] = node;
94         effect->inform_added(this);
95         return node;
96 }
97
98 void EffectChain::connect_nodes(Node *sender, Node *receiver)
99 {
100         sender->outgoing_links.push_back(receiver);
101         receiver->incoming_links.push_back(sender);
102 }
103
104 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
105 {
106         new_receiver->incoming_links = old_receiver->incoming_links;
107         old_receiver->incoming_links.clear();
108         
109         for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
110                 Node *sender = new_receiver->incoming_links[i];
111                 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
112                         if (sender->outgoing_links[j] == old_receiver) {
113                                 sender->outgoing_links[j] = new_receiver;
114                         }
115                 }
116         }       
117 }
118
119 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
120 {
121         new_sender->outgoing_links = old_sender->outgoing_links;
122         old_sender->outgoing_links.clear();
123         
124         for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
125                 Node *receiver = new_sender->outgoing_links[i];
126                 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
127                         if (receiver->incoming_links[j] == old_sender) {
128                                 receiver->incoming_links[j] = new_sender;
129                         }
130                 }
131         }       
132 }
133
134 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
135 {
136         for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
137                 if (sender->outgoing_links[i] == receiver) {
138                         sender->outgoing_links[i] = middle;
139                         middle->incoming_links.push_back(sender);
140                 }
141         }
142         for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
143                 if (receiver->incoming_links[i] == sender) {
144                         receiver->incoming_links[i] = middle;
145                         middle->outgoing_links.push_back(receiver);
146                 }
147         }
148
149         assert(middle->incoming_links.size() == middle->effect->num_inputs());
150 }
151
152 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
153 {
154         if (node->output_gamma_curve == GAMMA_LINEAR &&
155             node->effect->effect_type_id() != "GammaCompressionEffect") {
156                 return;
157         }
158         if (node->effect->num_inputs() == 0) {
159                 nonlinear_inputs->push_back(node);
160         } else {
161                 assert(node->effect->num_inputs() == node->incoming_links.size());
162                 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
163                         find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
164                 }
165         }
166 }
167
168 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
169 {
170         assert(!finalized);
171         assert(inputs.size() == effect->num_inputs());
172         Node *node = add_node(effect);
173         for (unsigned i = 0; i < inputs.size(); ++i) {
174                 assert(node_map.count(inputs[i]) != 0);
175                 connect_nodes(node_map[inputs[i]], node);
176         }
177         return effect;
178 }
179
180 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
181 string replace_prefix(const string &text, const string &prefix)
182 {
183         string output;
184         size_t start = 0;
185
186         while (start < text.size()) {
187                 size_t pos = text.find("PREFIX(", start);
188                 if (pos == string::npos) {
189                         output.append(text.substr(start, string::npos));
190                         break;
191                 }
192
193                 output.append(text.substr(start, pos - start));
194                 output.append(prefix);
195                 output.append("_");
196
197                 pos += strlen("PREFIX(");
198         
199                 // Output stuff until we find the matching ), which we then eat.
200                 int depth = 1;
201                 size_t end_arg_pos = pos;
202                 while (end_arg_pos < text.size()) {
203                         if (text[end_arg_pos] == '(') {
204                                 ++depth;
205                         } else if (text[end_arg_pos] == ')') {
206                                 --depth;
207                                 if (depth == 0) {
208                                         break;
209                                 }
210                         }
211                         ++end_arg_pos;
212                 }
213                 output.append(text.substr(pos, end_arg_pos - pos));
214                 ++end_arg_pos;
215                 assert(depth == 0);
216                 start = end_arg_pos;
217         }
218         return output;
219 }
220
221 Phase *EffectChain::compile_glsl_program(
222         const vector<Node *> &inputs,
223         const vector<Node *> &effects)
224 {
225         Phase *phase = new Phase;
226         assert(!effects.empty());
227
228         // Deduplicate the inputs.
229         vector<Node *> true_inputs = inputs;
230         sort(true_inputs.begin(), true_inputs.end());
231         true_inputs.erase(unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
232
233         bool input_needs_mipmaps = false;
234         string frag_shader = read_file("header.frag");
235
236         // Create functions for all the texture inputs that we need.
237         for (unsigned i = 0; i < true_inputs.size(); ++i) {
238                 Node *input = true_inputs[i];
239                 char effect_id[256];
240                 sprintf(effect_id, "in%u", i);
241                 phase->effect_ids.insert(make_pair(input, effect_id));
242         
243                 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
244                 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
245                 frag_shader += "\treturn texture2D(tex_" + string(effect_id) + ", tc);\n";
246                 frag_shader += "}\n";
247                 frag_shader += "\n";
248         }
249
250         vector<Node *> sorted_effects = topological_sort(effects);
251
252         for (unsigned i = 0; i < sorted_effects.size(); ++i) {
253                 Node *node = sorted_effects[i];
254                 char effect_id[256];
255                 sprintf(effect_id, "eff%u", i);
256                 phase->effect_ids.insert(make_pair(node, effect_id));
257
258                 if (node->incoming_links.size() == 1) {
259                         frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
260                 } else {
261                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
262                                 char buf[256];
263                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
264                                 frag_shader += buf;
265                         }
266                 }
267         
268                 frag_shader += "\n";
269                 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
270                 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), effect_id);
271                 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
272                 frag_shader += "#undef PREFIX\n";
273                 frag_shader += "#undef FUNCNAME\n";
274                 if (node->incoming_links.size() == 1) {
275                         frag_shader += "#undef INPUT\n";
276                 } else {
277                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
278                                 char buf[256];
279                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
280                                 frag_shader += buf;
281                         }
282                 }
283                 frag_shader += "\n";
284
285                 input_needs_mipmaps |= node->effect->needs_mipmaps();
286         }
287         for (unsigned i = 0; i < sorted_effects.size(); ++i) {
288                 Node *node = sorted_effects[i];
289                 if (node->effect->num_inputs() == 0) {
290                         CHECK(node->effect->set_int("needs_mipmaps", input_needs_mipmaps));
291                 }
292         }
293         frag_shader += string("#define INPUT ") + phase->effect_ids[sorted_effects.back()] + "\n";
294         frag_shader.append(read_file("footer.frag"));
295
296         phase->glsl_program_num = resource_pool->compile_glsl_program(read_file("vs.vert"), frag_shader);
297         phase->input_needs_mipmaps = input_needs_mipmaps;
298         phase->inputs = true_inputs;
299         phase->effects = sorted_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?
315         // We need to keep track of it, as an effect with multiple outputs
316         // could otherwise be calculated multiple times.
317         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         vector<Node *> this_phase_inputs;
323         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         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         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 inputs
343                         // (either true inputs or phase outputs). We special-case inputs,
344                         // and then deduplicate phase outputs in compile_glsl_program().
345                         if (node->effect->num_inputs() == 0) {
346                                 if (find(this_phase_effects.begin(), this_phase_effects.end(), node) != this_phase_effects.end()) {
347                                         continue;
348                                 }
349                         } else {
350                                 assert(completed_effects.count(node) == 0);
351                         }
352
353                         this_phase_effects.push_back(node);
354                         completed_effects.insert(node);
355
356                         // Find all the dependencies of this effect, and add them to the stack.
357                         vector<Node *> deps = node->incoming_links;
358                         assert(node->effect->num_inputs() == deps.size());
359                         for (unsigned i = 0; i < deps.size(); ++i) {
360                                 bool start_new_phase = false;
361
362                                 if (node->effect->needs_texture_bounce() &&
363                                     !deps[i]->effect->is_single_texture()) {
364                                         start_new_phase = true;
365                                 }
366
367                                 if (deps[i]->outgoing_links.size() > 1) {
368                                         if (!deps[i]->effect->is_single_texture()) {
369                                                 // More than one effect uses this as the input,
370                                                 // and it is not a texture itself.
371                                                 // The easiest thing to do (and probably also the safest
372                                                 // performance-wise in most cases) is to bounce it to a texture
373                                                 // and then let the next passes read from that.
374                                                 start_new_phase = true;
375                                         } else {
376                                                 assert(deps[i]->effect->num_inputs() == 0);
377
378                                                 // For textures, we try to be slightly more clever;
379                                                 // if none of our outputs need a bounce, we don't bounce
380                                                 // but instead simply use the effect many times.
381                                                 //
382                                                 // Strictly speaking, we could bounce it for some outputs
383                                                 // and use it directly for others, but the processing becomes
384                                                 // somewhat simpler if the effect is only used in one such way.
385                                                 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
386                                                         Node *rdep = deps[i]->outgoing_links[j];
387                                                         start_new_phase |= rdep->effect->needs_texture_bounce();
388                                                 }
389                                         }
390                                 }
391
392                                 if (deps[i]->effect->changes_output_size()) {
393                                         start_new_phase = true;
394                                 }
395
396                                 if (start_new_phase) {
397                                         effects_todo_other_phases.push(deps[i]);
398                                         this_phase_inputs.push_back(deps[i]);
399                                 } else {
400                                         effects_todo_this_phase.push(deps[i]);
401                                 }
402                         }
403                         continue;
404                 }
405
406                 // No more effects to do this phase. Take all the ones we have,
407                 // and create a GLSL program for it.
408                 if (!this_phase_effects.empty()) {
409                         reverse(this_phase_effects.begin(), this_phase_effects.end());
410                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
411                         this_phase_effects.back()->phase = phases.back();
412                         this_phase_inputs.clear();
413                         this_phase_effects.clear();
414                 }
415                 assert(this_phase_inputs.empty());
416                 assert(this_phase_effects.empty());
417
418                 // If we have no effects left, exit.
419                 if (effects_todo_other_phases.empty()) {
420                         break;
421                 }
422
423                 Node *node = effects_todo_other_phases.top();
424                 effects_todo_other_phases.pop();
425
426                 if (completed_effects.count(node) == 0) {
427                         // Start a new phase, calculating from this effect.
428                         effects_todo_this_phase.push(node);
429                 }
430         }
431
432         // Finally, since the phases are found from the output but must be executed
433         // from the input(s), reverse them, too.
434         reverse(phases.begin(), phases.end());
435 }
436
437 void EffectChain::output_dot(const char *filename)
438 {
439         if (movit_debug_level != MOVIT_DEBUG_ON) {
440                 return;
441         }
442
443         FILE *fp = fopen(filename, "w");
444         if (fp == NULL) {
445                 perror(filename);
446                 exit(1);
447         }
448
449         fprintf(fp, "digraph G {\n");
450         fprintf(fp, "  output [shape=box label=\"(output)\"];\n");
451         for (unsigned i = 0; i < nodes.size(); ++i) {
452                 // Find out which phase this event belongs to.
453                 vector<int> in_phases;
454                 for (unsigned j = 0; j < phases.size(); ++j) {
455                         const Phase* p = phases[j];
456                         if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
457                                 in_phases.push_back(j);
458                         }
459                 }
460
461                 if (in_phases.empty()) {
462                         fprintf(fp, "  n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
463                 } else if (in_phases.size() == 1) {
464                         fprintf(fp, "  n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
465                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
466                                 (in_phases[0] % 8) + 1);
467                 } else {
468                         // If we had new enough Graphviz, style="wedged" would probably be ideal here.
469                         // But alas.
470                         fprintf(fp, "  n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
471                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
472                                 (in_phases[0] % 8) + 1);
473                 }
474
475                 char from_node_id[256];
476                 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
477
478                 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
479                         char to_node_id[256];
480                         snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
481
482                         vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
483                         output_dot_edge(fp, from_node_id, to_node_id, labels);
484                 }
485
486                 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
487                         // Output node.
488                         vector<string> labels = get_labels_for_edge(nodes[i], NULL);
489                         output_dot_edge(fp, from_node_id, "output", labels);
490                 }
491         }
492         fprintf(fp, "}\n");
493
494         fclose(fp);
495 }
496
497 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
498 {
499         vector<string> labels;
500
501         if (to != NULL && to->effect->needs_texture_bounce()) {
502                 labels.push_back("needs_bounce");
503         }
504         if (from->effect->changes_output_size()) {
505                 labels.push_back("resize");
506         }
507
508         switch (from->output_color_space) {
509         case COLORSPACE_INVALID:
510                 labels.push_back("spc[invalid]");
511                 break;
512         case COLORSPACE_REC_601_525:
513                 labels.push_back("spc[rec601-525]");
514                 break;
515         case COLORSPACE_REC_601_625:
516                 labels.push_back("spc[rec601-625]");
517                 break;
518         default:
519                 break;
520         }
521
522         switch (from->output_gamma_curve) {
523         case GAMMA_INVALID:
524                 labels.push_back("gamma[invalid]");
525                 break;
526         case GAMMA_sRGB:
527                 labels.push_back("gamma[sRGB]");
528                 break;
529         case GAMMA_REC_601:  // and GAMMA_REC_709
530                 labels.push_back("gamma[rec601/709]");
531                 break;
532         default:
533                 break;
534         }
535
536         switch (from->output_alpha_type) {
537         case ALPHA_INVALID:
538                 labels.push_back("alpha[invalid]");
539                 break;
540         case ALPHA_BLANK:
541                 labels.push_back("alpha[blank]");
542                 break;
543         case ALPHA_POSTMULTIPLIED:
544                 labels.push_back("alpha[postmult]");
545                 break;
546         default:
547                 break;
548         }
549
550         return labels;
551 }
552
553 void EffectChain::output_dot_edge(FILE *fp,
554                                   const string &from_node_id,
555                                   const string &to_node_id,
556                                   const vector<string> &labels)
557 {
558         if (labels.empty()) {
559                 fprintf(fp, "  %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
560         } else {
561                 string label = labels[0];
562                 for (unsigned k = 1; k < labels.size(); ++k) {
563                         label += ", " + labels[k];
564                 }
565                 fprintf(fp, "  %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
566         }
567 }
568
569 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
570 {
571         unsigned scaled_width, scaled_height;
572
573         if (float(width) * aspect_denom >= float(height) * aspect_nom) {
574                 // Same aspect, or W/H > aspect (image is wider than the frame).
575                 // In either case, keep width, and adjust height.
576                 scaled_width = width;
577                 scaled_height = lrintf(width * aspect_denom / aspect_nom);
578         } else {
579                 // W/H < aspect (image is taller than the frame), so keep height,
580                 // and adjust width.
581                 scaled_width = lrintf(height * aspect_nom / aspect_denom);
582                 scaled_height = height;
583         }
584
585         // We should be consistently larger or smaller then the existing choice,
586         // since we have the same aspect.
587         assert(!(scaled_width < *output_width && scaled_height > *output_height));
588         assert(!(scaled_height < *output_height && scaled_width > *output_width));
589
590         if (scaled_width >= *output_width && scaled_height >= *output_height) {
591                 *output_width = scaled_width;
592                 *output_height = scaled_height;
593         }
594 }
595
596 // Propagate input texture sizes throughout, and inform effects downstream.
597 // (Like a lot of other code, we depend on effects being in topological order.)
598 void EffectChain::inform_input_sizes(Phase *phase)
599 {
600         // All effects that have a defined size (inputs and RTT inputs)
601         // get that. Reset all others.
602         for (unsigned i = 0; i < phase->effects.size(); ++i) {
603                 Node *node = phase->effects[i];
604                 if (node->effect->num_inputs() == 0) {
605                         Input *input = static_cast<Input *>(node->effect);
606                         node->output_width = input->get_width();
607                         node->output_height = input->get_height();
608                         assert(node->output_width != 0);
609                         assert(node->output_height != 0);
610                 } else {
611                         node->output_width = node->output_height = 0;
612                 }
613         }
614         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
615                 Node *input = phase->inputs[i];
616                 input->output_width = input->phase->virtual_output_width;
617                 input->output_height = input->phase->virtual_output_height;
618                 assert(input->output_width != 0);
619                 assert(input->output_height != 0);
620         }
621
622         // Now propagate from the inputs towards the end, and inform as we go.
623         // The rules are simple:
624         //
625         //   1. Don't touch effects that already have given sizes (ie., inputs).
626         //   2. If all of your inputs have the same size, that will be your output size.
627         //   3. Otherwise, your output size is 0x0.
628         for (unsigned i = 0; i < phase->effects.size(); ++i) {
629                 Node *node = phase->effects[i];
630                 if (node->effect->num_inputs() == 0) {
631                         continue;
632                 }
633                 unsigned this_output_width = 0;
634                 unsigned this_output_height = 0;
635                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
636                         Node *input = node->incoming_links[j];
637                         node->effect->inform_input_size(j, input->output_width, input->output_height);
638                         if (j == 0) {
639                                 this_output_width = input->output_width;
640                                 this_output_height = input->output_height;
641                         } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
642                                 // Inputs disagree.
643                                 this_output_width = 0;
644                                 this_output_height = 0;
645                         }
646                 }
647                 node->output_width = this_output_width;
648                 node->output_height = this_output_height;
649         }
650 }
651
652 // Note: You should call inform_input_sizes() before this, as the last effect's
653 // desired output size might change based on the inputs.
654 void EffectChain::find_output_size(Phase *phase)
655 {
656         Node *output_node = phase->effects.back();
657
658         // If the last effect explicitly sets an output size, use that.
659         if (output_node->effect->changes_output_size()) {
660                 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
661                                                      &phase->virtual_output_width, &phase->virtual_output_height);
662                 return;
663         }
664
665         // If all effects have the same size, use that.
666         unsigned output_width = 0, output_height = 0;
667         bool all_inputs_same_size = true;
668
669         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
670                 Node *input = phase->inputs[i];
671                 assert(input->phase->output_width != 0);
672                 assert(input->phase->output_height != 0);
673                 if (output_width == 0 && output_height == 0) {
674                         output_width = input->phase->virtual_output_width;
675                         output_height = input->phase->virtual_output_height;
676                 } else if (output_width != input->phase->virtual_output_width ||
677                            output_height != input->phase->virtual_output_height) {
678                         all_inputs_same_size = false;
679                 }
680         }
681         for (unsigned i = 0; i < phase->effects.size(); ++i) {
682                 Effect *effect = phase->effects[i]->effect;
683                 if (effect->num_inputs() != 0) {
684                         continue;
685                 }
686
687                 Input *input = static_cast<Input *>(effect);
688                 if (output_width == 0 && output_height == 0) {
689                         output_width = input->get_width();
690                         output_height = input->get_height();
691                 } else if (output_width != input->get_width() ||
692                            output_height != input->get_height()) {
693                         all_inputs_same_size = false;
694                 }
695         }
696
697         if (all_inputs_same_size) {
698                 assert(output_width != 0);
699                 assert(output_height != 0);
700                 phase->virtual_output_width = phase->output_width = output_width;
701                 phase->virtual_output_height = phase->output_height = output_height;
702                 return;
703         }
704
705         // If not, fit all the inputs into the current aspect, and select the largest one. 
706         output_width = 0;
707         output_height = 0;
708         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
709                 Node *input = phase->inputs[i];
710                 assert(input->phase->output_width != 0);
711                 assert(input->phase->output_height != 0);
712                 size_rectangle_to_fit(input->phase->output_width, input->phase->output_height, &output_width, &output_height);
713         }
714         for (unsigned i = 0; i < phase->effects.size(); ++i) {
715                 Effect *effect = phase->effects[i]->effect;
716                 if (effect->num_inputs() != 0) {
717                         continue;
718                 }
719
720                 Input *input = static_cast<Input *>(effect);
721                 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
722         }
723         assert(output_width != 0);
724         assert(output_height != 0);
725         phase->virtual_output_width = phase->output_width = output_width;
726         phase->virtual_output_height = phase->output_height = output_height;
727 }
728
729 void EffectChain::sort_all_nodes_topologically()
730 {
731         nodes = topological_sort(nodes);
732 }
733
734 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
735 {
736         set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
737         vector<Node *> sorted_list;
738         for (unsigned i = 0; i < nodes.size(); ++i) {
739                 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
740         }
741         reverse(sorted_list.begin(), sorted_list.end());
742         return sorted_list;
743 }
744
745 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
746 {
747         if (nodes_left_to_visit->count(node) == 0) {
748                 return;
749         }
750         nodes_left_to_visit->erase(node);
751         for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
752                 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
753         }
754         sorted_list->push_back(node);
755 }
756
757 void EffectChain::find_color_spaces_for_inputs()
758 {
759         for (unsigned i = 0; i < nodes.size(); ++i) {
760                 Node *node = nodes[i];
761                 if (node->disabled) {
762                         continue;
763                 }
764                 if (node->incoming_links.size() == 0) {
765                         Input *input = static_cast<Input *>(node->effect);
766                         node->output_color_space = input->get_color_space();
767                         node->output_gamma_curve = input->get_gamma_curve();
768
769                         Effect::AlphaHandling alpha_handling = input->alpha_handling();
770                         switch (alpha_handling) {
771                         case Effect::OUTPUT_BLANK_ALPHA:
772                                 node->output_alpha_type = ALPHA_BLANK;
773                                 break;
774                         case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
775                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
776                                 break;
777                         case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
778                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
779                                 break;
780                         case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
781                         case Effect::DONT_CARE_ALPHA_TYPE:
782                         default:
783                                 assert(false);
784                         }
785
786                         if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
787                                 assert(node->output_gamma_curve == GAMMA_LINEAR);
788                         }
789                 }
790         }
791 }
792
793 // Propagate gamma and color space information as far as we can in the graph.
794 // The rules are simple: Anything where all the inputs agree, get that as
795 // output as well. Anything else keeps having *_INVALID.
796 void EffectChain::propagate_gamma_and_color_space()
797 {
798         // We depend on going through the nodes in order.
799         sort_all_nodes_topologically();
800
801         for (unsigned i = 0; i < nodes.size(); ++i) {
802                 Node *node = nodes[i];
803                 if (node->disabled) {
804                         continue;
805                 }
806                 assert(node->incoming_links.size() == node->effect->num_inputs());
807                 if (node->incoming_links.size() == 0) {
808                         assert(node->output_color_space != COLORSPACE_INVALID);
809                         assert(node->output_gamma_curve != GAMMA_INVALID);
810                         continue;
811                 }
812
813                 Colorspace color_space = node->incoming_links[0]->output_color_space;
814                 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
815                 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
816                         if (node->incoming_links[j]->output_color_space != color_space) {
817                                 color_space = COLORSPACE_INVALID;
818                         }
819                         if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
820                                 gamma_curve = GAMMA_INVALID;
821                         }
822                 }
823
824                 // The conversion effects already have their outputs set correctly,
825                 // so leave them alone.
826                 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
827                         node->output_color_space = color_space;
828                 }               
829                 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
830                     node->effect->effect_type_id() != "GammaExpansionEffect") {
831                         node->output_gamma_curve = gamma_curve;
832                 }               
833         }
834 }
835
836 // Propagate alpha information as far as we can in the graph.
837 // Similar to propagate_gamma_and_color_space().
838 void EffectChain::propagate_alpha()
839 {
840         // We depend on going through the nodes in order.
841         sort_all_nodes_topologically();
842
843         for (unsigned i = 0; i < nodes.size(); ++i) {
844                 Node *node = nodes[i];
845                 if (node->disabled) {
846                         continue;
847                 }
848                 assert(node->incoming_links.size() == node->effect->num_inputs());
849                 if (node->incoming_links.size() == 0) {
850                         assert(node->output_alpha_type != ALPHA_INVALID);
851                         continue;
852                 }
853
854                 // The alpha multiplication/division effects are special cases.
855                 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
856                         assert(node->incoming_links.size() == 1);
857                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
858                         node->output_alpha_type = ALPHA_PREMULTIPLIED;
859                         continue;
860                 }
861                 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
862                         assert(node->incoming_links.size() == 1);
863                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
864                         node->output_alpha_type = ALPHA_POSTMULTIPLIED;
865                         continue;
866                 }
867
868                 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
869                 // because they are the only one that _need_ postmultiplied alpha.
870                 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
871                     node->effect->effect_type_id() == "GammaExpansionEffect") {
872                         assert(node->incoming_links.size() == 1);
873                         if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
874                                 node->output_alpha_type = ALPHA_BLANK;
875                         } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
876                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
877                         } else {
878                                 node->output_alpha_type = ALPHA_INVALID;
879                         }
880                         continue;
881                 }
882
883                 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
884                 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
885                 // taken care of above. Rationale: Even if you could imagine
886                 // e.g. an effect that took in an image and set alpha=1.0
887                 // unconditionally, it wouldn't make any sense to have it as
888                 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
889                 // got its input pre- or postmultiplied, so it wouldn't know
890                 // whether to divide away the old alpha or not.
891                 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
892                 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
893                        alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
894                        alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
895
896                 // If the node has multiple inputs, check that they are all valid and
897                 // the same.
898                 bool any_invalid = false;
899                 bool any_premultiplied = false;
900                 bool any_postmultiplied = false;
901
902                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
903                         switch (node->incoming_links[j]->output_alpha_type) {
904                         case ALPHA_INVALID:
905                                 any_invalid = true;
906                                 break;
907                         case ALPHA_BLANK:
908                                 // Blank is good as both pre- and postmultiplied alpha,
909                                 // so just ignore it.
910                                 break;
911                         case ALPHA_PREMULTIPLIED:
912                                 any_premultiplied = true;
913                                 break;
914                         case ALPHA_POSTMULTIPLIED:
915                                 any_postmultiplied = true;
916                                 break;
917                         default:
918                                 assert(false);
919                         }
920                 }
921
922                 if (any_invalid) {
923                         node->output_alpha_type = ALPHA_INVALID;
924                         continue;
925                 }
926
927                 // Inputs must be of the same type.
928                 if (any_premultiplied && any_postmultiplied) {
929                         node->output_alpha_type = ALPHA_INVALID;
930                         continue;
931                 }
932
933                 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
934                     alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
935                         // If the effect has asked for premultiplied alpha, check that it has got it.
936                         if (any_postmultiplied) {
937                                 node->output_alpha_type = ALPHA_INVALID;
938                         } else if (!any_premultiplied &&
939                                    alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
940                                 // Blank input alpha, and the effect preserves blank alpha.
941                                 node->output_alpha_type = ALPHA_BLANK;
942                         } else {
943                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
944                         }
945                 } else {
946                         // OK, all inputs are the same, and this effect is not going
947                         // to change it.
948                         assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
949                         if (any_premultiplied) {
950                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
951                         } else if (any_postmultiplied) {
952                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
953                         } else {
954                                 node->output_alpha_type = ALPHA_BLANK;
955                         }
956                 }
957         }
958 }
959
960 bool EffectChain::node_needs_colorspace_fix(Node *node)
961 {
962         if (node->disabled) {
963                 return false;
964         }
965         if (node->effect->num_inputs() == 0) {
966                 return false;
967         }
968
969         // propagate_gamma_and_color_space() has already set our output
970         // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
971         if (node->output_color_space == COLORSPACE_INVALID) {
972                 return true;
973         }
974         return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
975 }
976
977 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
978 // the graph. Our strategy is not always optimal, but quite simple:
979 // Find an effect that's as early as possible where the inputs are of
980 // unacceptable colorspaces (that is, either different, or, if the effect only
981 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
982 // propagate the information anew, and repeat until there are no more such
983 // effects.
984 void EffectChain::fix_internal_color_spaces()
985 {
986         unsigned colorspace_propagation_pass = 0;
987         bool found_any;
988         do {
989                 found_any = false;
990                 for (unsigned i = 0; i < nodes.size(); ++i) {
991                         Node *node = nodes[i];
992                         if (!node_needs_colorspace_fix(node)) {
993                                 continue;
994                         }
995
996                         // Go through each input that is not sRGB, and insert
997                         // a colorspace conversion after it.
998                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
999                                 Node *input = node->incoming_links[j];
1000                                 assert(input->output_color_space != COLORSPACE_INVALID);
1001                                 if (input->output_color_space == COLORSPACE_sRGB) {
1002                                         continue;
1003                                 }
1004                                 Node *conversion = add_node(new ColorspaceConversionEffect());
1005                                 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1006                                 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1007                                 conversion->output_color_space = COLORSPACE_sRGB;
1008                                 replace_sender(input, conversion);
1009                                 connect_nodes(input, conversion);
1010                         }
1011
1012                         // Re-sort topologically, and propagate the new information.
1013                         propagate_gamma_and_color_space();
1014                         
1015                         found_any = true;
1016                         break;
1017                 }
1018         
1019                 char filename[256];
1020                 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1021                 output_dot(filename);
1022                 assert(colorspace_propagation_pass < 100);
1023         } while (found_any);
1024
1025         for (unsigned i = 0; i < nodes.size(); ++i) {
1026                 Node *node = nodes[i];
1027                 if (node->disabled) {
1028                         continue;
1029                 }
1030                 assert(node->output_color_space != COLORSPACE_INVALID);
1031         }
1032 }
1033
1034 bool EffectChain::node_needs_alpha_fix(Node *node)
1035 {
1036         if (node->disabled) {
1037                 return false;
1038         }
1039
1040         // propagate_alpha() has already set our output to ALPHA_INVALID if the
1041         // inputs differ or we are otherwise in mismatch, so we can rely on that.
1042         return (node->output_alpha_type == ALPHA_INVALID);
1043 }
1044
1045 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1046 // the graph. Similar to fix_internal_color_spaces().
1047 void EffectChain::fix_internal_alpha(unsigned step)
1048 {
1049         unsigned alpha_propagation_pass = 0;
1050         bool found_any;
1051         do {
1052                 found_any = false;
1053                 for (unsigned i = 0; i < nodes.size(); ++i) {
1054                         Node *node = nodes[i];
1055                         if (!node_needs_alpha_fix(node)) {
1056                                 continue;
1057                         }
1058
1059                         // If we need to fix up GammaExpansionEffect, then clearly something
1060                         // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1061                         // is meaningless.
1062                         assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1063
1064                         AlphaType desired_type = ALPHA_PREMULTIPLIED;
1065
1066                         // GammaCompressionEffect is special; it needs postmultiplied alpha.
1067                         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1068                                 assert(node->incoming_links.size() == 1);
1069                                 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1070                                 desired_type = ALPHA_POSTMULTIPLIED;
1071                         }
1072
1073                         // Go through each input that is not premultiplied alpha, and insert
1074                         // a conversion before it.
1075                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1076                                 Node *input = node->incoming_links[j];
1077                                 assert(input->output_alpha_type != ALPHA_INVALID);
1078                                 if (input->output_alpha_type == desired_type ||
1079                                     input->output_alpha_type == ALPHA_BLANK) {
1080                                         continue;
1081                                 }
1082                                 Node *conversion;
1083                                 if (desired_type == ALPHA_PREMULTIPLIED) {
1084                                         conversion = add_node(new AlphaMultiplicationEffect());
1085                                 } else {
1086                                         conversion = add_node(new AlphaDivisionEffect());
1087                                 }
1088                                 conversion->output_alpha_type = desired_type;
1089                                 replace_sender(input, conversion);
1090                                 connect_nodes(input, conversion);
1091                         }
1092
1093                         // Re-sort topologically, and propagate the new information.
1094                         propagate_gamma_and_color_space();
1095                         propagate_alpha();
1096                         
1097                         found_any = true;
1098                         break;
1099                 }
1100         
1101                 char filename[256];
1102                 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1103                 output_dot(filename);
1104                 assert(alpha_propagation_pass < 100);
1105         } while (found_any);
1106
1107         for (unsigned i = 0; i < nodes.size(); ++i) {
1108                 Node *node = nodes[i];
1109                 if (node->disabled) {
1110                         continue;
1111                 }
1112                 assert(node->output_alpha_type != ALPHA_INVALID);
1113         }
1114 }
1115
1116 // Make so that the output is in the desired color space.
1117 void EffectChain::fix_output_color_space()
1118 {
1119         Node *output = find_output_node();
1120         if (output->output_color_space != output_format.color_space) {
1121                 Node *conversion = add_node(new ColorspaceConversionEffect());
1122                 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1123                 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1124                 conversion->output_color_space = output_format.color_space;
1125                 connect_nodes(output, conversion);
1126                 propagate_alpha();
1127                 propagate_gamma_and_color_space();
1128         }
1129 }
1130
1131 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1132 void EffectChain::fix_output_alpha()
1133 {
1134         Node *output = find_output_node();
1135         assert(output->output_alpha_type != ALPHA_INVALID);
1136         if (output->output_alpha_type == ALPHA_BLANK) {
1137                 // No alpha output, so we don't care.
1138                 return;
1139         }
1140         if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1141             output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1142                 Node *conversion = add_node(new AlphaDivisionEffect());
1143                 connect_nodes(output, conversion);
1144                 propagate_alpha();
1145                 propagate_gamma_and_color_space();
1146         }
1147         if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1148             output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1149                 Node *conversion = add_node(new AlphaMultiplicationEffect());
1150                 connect_nodes(output, conversion);
1151                 propagate_alpha();
1152                 propagate_gamma_and_color_space();
1153         }
1154 }
1155
1156 bool EffectChain::node_needs_gamma_fix(Node *node)
1157 {
1158         if (node->disabled) {
1159                 return false;
1160         }
1161
1162         // Small hack since the output is not an explicit node:
1163         // If we are the last node and our output is in the wrong
1164         // space compared to EffectChain's output, we need to fix it.
1165         // This will only take us to linear, but fix_output_gamma()
1166         // will come and take us to the desired output gamma
1167         // if it is needed.
1168         //
1169         // This needs to be before everything else, since it could
1170         // even apply to inputs (if they are the only effect).
1171         if (node->outgoing_links.empty() &&
1172             node->output_gamma_curve != output_format.gamma_curve &&
1173             node->output_gamma_curve != GAMMA_LINEAR) {
1174                 return true;
1175         }
1176
1177         if (node->effect->num_inputs() == 0) {
1178                 return false;
1179         }
1180
1181         // propagate_gamma_and_color_space() has already set our output
1182         // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1183         // except for GammaCompressionEffect.
1184         if (node->output_gamma_curve == GAMMA_INVALID) {
1185                 return true;
1186         }
1187         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1188                 assert(node->incoming_links.size() == 1);
1189                 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1190         }
1191
1192         return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1193 }
1194
1195 // Very similar to fix_internal_color_spaces(), but for gamma.
1196 // There is one difference, though; before we start adding conversion nodes,
1197 // we see if we can get anything out of asking the sources to deliver
1198 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1199 // does that part, while fix_internal_gamma_by_inserting_nodes()
1200 // inserts nodes as needed afterwards.
1201 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1202 {
1203         unsigned gamma_propagation_pass = 0;
1204         bool found_any;
1205         do {
1206                 found_any = false;
1207                 for (unsigned i = 0; i < nodes.size(); ++i) {
1208                         Node *node = nodes[i];
1209                         if (!node_needs_gamma_fix(node)) {
1210                                 continue;
1211                         }
1212
1213                         // See if all inputs can give us linear gamma. If not, leave it.
1214                         vector<Node *> nonlinear_inputs;
1215                         find_all_nonlinear_inputs(node, &nonlinear_inputs);
1216                         assert(!nonlinear_inputs.empty());
1217
1218                         bool all_ok = true;
1219                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1220                                 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1221                                 all_ok &= input->can_output_linear_gamma();
1222                         }
1223
1224                         if (!all_ok) {
1225                                 continue;
1226                         }
1227
1228                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1229                                 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1230                                 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1231                         }
1232
1233                         // Re-sort topologically, and propagate the new information.
1234                         propagate_gamma_and_color_space();
1235                         
1236                         found_any = true;
1237                         break;
1238                 }
1239         
1240                 char filename[256];
1241                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1242                 output_dot(filename);
1243                 assert(gamma_propagation_pass < 100);
1244         } while (found_any);
1245 }
1246
1247 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1248 {
1249         unsigned gamma_propagation_pass = 0;
1250         bool found_any;
1251         do {
1252                 found_any = false;
1253                 for (unsigned i = 0; i < nodes.size(); ++i) {
1254                         Node *node = nodes[i];
1255                         if (!node_needs_gamma_fix(node)) {
1256                                 continue;
1257                         }
1258
1259                         // Special case: We could be an input and still be asked to
1260                         // fix our gamma; if so, we should be the only node
1261                         // (as node_needs_gamma_fix() would only return true in
1262                         // for an input in that case). That means we should insert
1263                         // a conversion node _after_ ourselves.
1264                         if (node->incoming_links.empty()) {
1265                                 assert(node->outgoing_links.empty());
1266                                 Node *conversion = add_node(new GammaExpansionEffect());
1267                                 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1268                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1269                                 connect_nodes(node, conversion);
1270                         }
1271
1272                         // If not, go through each input that is not linear gamma,
1273                         // and insert a gamma conversion after it.
1274                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1275                                 Node *input = node->incoming_links[j];
1276                                 assert(input->output_gamma_curve != GAMMA_INVALID);
1277                                 if (input->output_gamma_curve == GAMMA_LINEAR) {
1278                                         continue;
1279                                 }
1280                                 Node *conversion = add_node(new GammaExpansionEffect());
1281                                 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1282                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1283                                 replace_sender(input, conversion);
1284                                 connect_nodes(input, conversion);
1285                         }
1286
1287                         // Re-sort topologically, and propagate the new information.
1288                         propagate_alpha();
1289                         propagate_gamma_and_color_space();
1290                         
1291                         found_any = true;
1292                         break;
1293                 }
1294         
1295                 char filename[256];
1296                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1297                 output_dot(filename);
1298                 assert(gamma_propagation_pass < 100);
1299         } while (found_any);
1300
1301         for (unsigned i = 0; i < nodes.size(); ++i) {
1302                 Node *node = nodes[i];
1303                 if (node->disabled) {
1304                         continue;
1305                 }
1306                 assert(node->output_gamma_curve != GAMMA_INVALID);
1307         }
1308 }
1309
1310 // Make so that the output is in the desired gamma.
1311 // Note that this assumes linear input gamma, so it might create the need
1312 // for another pass of fix_internal_gamma().
1313 void EffectChain::fix_output_gamma()
1314 {
1315         Node *output = find_output_node();
1316         if (output->output_gamma_curve != output_format.gamma_curve) {
1317                 Node *conversion = add_node(new GammaCompressionEffect());
1318                 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1319                 conversion->output_gamma_curve = output_format.gamma_curve;
1320                 connect_nodes(output, conversion);
1321         }
1322 }
1323         
1324 // If the user has requested dither, add a DitherEffect right at the end
1325 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1326 // since dither is about the only effect that can _not_ be done in linear space.
1327 void EffectChain::add_dither_if_needed()
1328 {
1329         if (num_dither_bits == 0) {
1330                 return;
1331         }
1332         Node *output = find_output_node();
1333         Node *dither = add_node(new DitherEffect());
1334         CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1335         connect_nodes(output, dither);
1336
1337         dither_effect = dither->effect;
1338 }
1339
1340 // Find the output node. This is, simply, one that has no outgoing links.
1341 // If there are multiple ones, the graph is malformed (we do not support
1342 // multiple outputs right now).
1343 Node *EffectChain::find_output_node()
1344 {
1345         vector<Node *> output_nodes;
1346         for (unsigned i = 0; i < nodes.size(); ++i) {
1347                 Node *node = nodes[i];
1348                 if (node->disabled) {
1349                         continue;
1350                 }
1351                 if (node->outgoing_links.empty()) {
1352                         output_nodes.push_back(node);
1353                 }
1354         }
1355         assert(output_nodes.size() == 1);
1356         return output_nodes[0];
1357 }
1358
1359 void EffectChain::finalize()
1360 {
1361         // Save the current locale, and set it to C, so that we can output decimal
1362         // numbers with printf and be sure to get them in the format mandated by GLSL.
1363         char *saved_locale = setlocale(LC_NUMERIC, "C");
1364
1365         // Output the graph as it is before we do any conversions on it.
1366         output_dot("step0-start.dot");
1367
1368         // Give each effect in turn a chance to rewrite its own part of the graph.
1369         // Note that if more effects are added as part of this, they will be
1370         // picked up as part of the same for loop, since they are added at the end.
1371         for (unsigned i = 0; i < nodes.size(); ++i) {
1372                 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1373         }
1374         output_dot("step1-rewritten.dot");
1375
1376         find_color_spaces_for_inputs();
1377         output_dot("step2-input-colorspace.dot");
1378
1379         propagate_alpha();
1380         output_dot("step3-propagated-alpha.dot");
1381
1382         propagate_gamma_and_color_space();
1383         output_dot("step4-propagated-all.dot");
1384
1385         fix_internal_color_spaces();
1386         fix_internal_alpha(6);
1387         fix_output_color_space();
1388         output_dot("step7-output-colorspacefix.dot");
1389         fix_output_alpha();
1390         output_dot("step8-output-alphafix.dot");
1391
1392         // Note that we need to fix gamma after colorspace conversion,
1393         // because colorspace conversions might create needs for gamma conversions.
1394         // Also, we need to run an extra pass of fix_internal_gamma() after 
1395         // fixing the output gamma, as we only have conversions to/from linear,
1396         // and fix_internal_alpha() since GammaCompressionEffect needs
1397         // postmultiplied input.
1398         fix_internal_gamma_by_asking_inputs(9);
1399         fix_internal_gamma_by_inserting_nodes(10);
1400         fix_output_gamma();
1401         output_dot("step11-output-gammafix.dot");
1402         propagate_alpha();
1403         output_dot("step12-output-alpha-propagated.dot");
1404         fix_internal_alpha(13);
1405         output_dot("step14-output-alpha-fixed.dot");
1406         fix_internal_gamma_by_asking_inputs(15);
1407         fix_internal_gamma_by_inserting_nodes(16);
1408
1409         output_dot("step17-before-dither.dot");
1410
1411         add_dither_if_needed();
1412
1413         output_dot("step18-final.dot");
1414         
1415         // Construct all needed GLSL programs, starting at the output.
1416         construct_glsl_programs(find_output_node());
1417
1418         output_dot("step19-split-to-phases.dot");
1419
1420         assert(phases[0]->inputs.empty());
1421         
1422         finalized = true;
1423         setlocale(LC_NUMERIC, saved_locale);
1424 }
1425
1426 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1427 {
1428         assert(finalized);
1429
1430         // Save original viewport.
1431         GLuint x = 0, y = 0;
1432         GLuint fbo = 0;
1433
1434         if (width == 0 && height == 0) {
1435                 GLint viewport[4];
1436                 glGetIntegerv(GL_VIEWPORT, viewport);
1437                 x = viewport[0];
1438                 y = viewport[1];
1439                 width = viewport[2];
1440                 height = viewport[3];
1441         }
1442
1443         // Basic state.
1444         glDisable(GL_BLEND);
1445         check_error();
1446         glDisable(GL_DEPTH_TEST);
1447         check_error();
1448         glDepthMask(GL_FALSE);
1449         check_error();
1450
1451         if (phases.size() > 1) {
1452                 glGenFramebuffers(1, &fbo);
1453                 check_error();
1454                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1455                 check_error();
1456         }
1457
1458         set<Node *> generated_mipmaps;
1459
1460         // We choose the simplest option of having one texture per output,
1461         // since otherwise this turns into an (albeit simple) register allocation problem.
1462         map<Phase *, GLuint> output_textures;
1463
1464         for (unsigned phase = 0; phase < phases.size(); ++phase) {
1465                 // Find a texture for this phase.
1466                 inform_input_sizes(phases[phase]);
1467                 if (phase != phases.size() - 1) {
1468                         find_output_size(phases[phase]);
1469
1470                         GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height);
1471                         output_textures.insert(make_pair(phases[phase], tex_num));
1472                 }
1473
1474                 const GLuint glsl_program_num = phases[phase]->glsl_program_num;
1475                 check_error();
1476                 glUseProgram(glsl_program_num);
1477                 check_error();
1478
1479                 // Set up RTT inputs for this phase.
1480                 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
1481                         glActiveTexture(GL_TEXTURE0 + sampler);
1482                         Node *input = phases[phase]->inputs[sampler];
1483                         glBindTexture(GL_TEXTURE_2D, output_textures[input->phase]);
1484                         check_error();
1485                         if (phases[phase]->input_needs_mipmaps) {
1486                                 if (generated_mipmaps.count(input) == 0) {
1487                                         glGenerateMipmap(GL_TEXTURE_2D);
1488                                         check_error();
1489                                         generated_mipmaps.insert(input);
1490                                 }
1491                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1492                                 check_error();
1493                         } else {
1494                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1495                                 check_error();
1496                         }
1497                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1498                         check_error();
1499                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1500                         check_error();
1501
1502                         string texture_name = string("tex_") + phases[phase]->effect_ids[input];
1503                         glUniform1i(glGetUniformLocation(glsl_program_num, texture_name.c_str()), sampler);
1504                         check_error();
1505                 }
1506
1507                 // And now the output.
1508                 if (phase == phases.size() - 1) {
1509                         // Last phase goes to the output the user specified.
1510                         glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1511                         check_error();
1512                         GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1513                         assert(status == GL_FRAMEBUFFER_COMPLETE);
1514                         glViewport(x, y, width, height);
1515                         if (dither_effect != NULL) {
1516                                 CHECK(dither_effect->set_int("output_width", width));
1517                                 CHECK(dither_effect->set_int("output_height", height));
1518                         }
1519                 } else {
1520                         glFramebufferTexture2D(
1521                                 GL_FRAMEBUFFER,
1522                                 GL_COLOR_ATTACHMENT0,
1523                                 GL_TEXTURE_2D,
1524                                 output_textures[phases[phase]],
1525                                 0);
1526                         check_error();
1527                         GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1528                         assert(status == GL_FRAMEBUFFER_COMPLETE);
1529                         glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
1530                 }
1531
1532                 // Give the required parameters to all the effects.
1533                 unsigned sampler_num = phases[phase]->inputs.size();
1534                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1535                         Node *node = phases[phase]->effects[i];
1536                         node->effect->set_gl_state(glsl_program_num, phases[phase]->effect_ids[node], &sampler_num);
1537                         check_error();
1538                 }
1539
1540                 // Now draw!
1541                 float vertices[] = {
1542                         0.0f, 1.0f,
1543                         0.0f, 0.0f,
1544                         1.0f, 1.0f,
1545                         1.0f, 0.0f
1546                 };
1547
1548                 GLuint vao;
1549                 glGenVertexArrays(1, &vao);
1550                 check_error();
1551                 glBindVertexArray(vao);
1552                 check_error();
1553
1554                 GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1555                 GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices);  // Same as vertices.
1556
1557                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1558                 check_error();
1559
1560                 cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1561                 cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1562
1563                 glUseProgram(0);
1564                 check_error();
1565
1566                 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
1567                         Node *node = phases[phase]->effects[i];
1568                         node->effect->clear_gl_state();
1569                 }
1570
1571                 glDeleteVertexArrays(1, &vao);
1572                 check_error();
1573         }
1574
1575         for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1576              texture_it != output_textures.end();
1577              ++texture_it) {
1578                 resource_pool->release_2d_texture(texture_it->second);
1579         }
1580
1581         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1582         check_error();
1583
1584         if (fbo != 0) {
1585                 glDeleteFramebuffers(1, &fbo);
1586                 check_error();
1587         }
1588 }
1589
1590 }  // namespace movit