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