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