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