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