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