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