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