]> git.sesse.net Git - movit/blob - effect_chain.cpp
Fix some warnings.
[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         string vert_shader = read_version_dependent_file("vs", "vert");
559
560         // If we're the last phase and need to flip the picture to compensate for
561         // the origin, tell the vertex or compute shader so.
562         bool is_last_phase;
563         if (has_dummy_effect) {
564                 is_last_phase = (phase->output_node->outgoing_links.size() == 1 &&
565                         phase->output_node->outgoing_links[0]->effect->effect_type_id() == "ComputeShaderOutputDisplayEffect");
566         } else {
567                 is_last_phase = phase->output_node->outgoing_links.empty();
568         }
569         if (is_last_phase && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
570                 if (phase->is_compute_shader) {
571                         frag_shader_header += "#define FLIP_ORIGIN 1\n";
572                 } else {
573                         const string needle = "#define FLIP_ORIGIN 0";
574                         size_t pos = vert_shader.find(needle);
575                         assert(pos != string::npos);
576
577                         vert_shader[pos + needle.size() - 1] = '1';
578                 }
579         }
580
581         frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
582
583         if (phase->is_compute_shader) {
584                 phase->glsl_program_num = resource_pool->compile_glsl_compute_program(frag_shader);
585
586                 Uniform<int> uniform;
587                 uniform.name = "outbuf";
588                 uniform.value = &phase->outbuf_image_unit;
589                 uniform.prefix = "tex";
590                 uniform.num_values = 1;
591                 uniform.location = -1;
592                 phase->uniforms_image2d.push_back(uniform);
593         } else {
594                 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader, frag_shader_outputs);
595         }
596         GLint position_attribute_index = glGetAttribLocation(phase->glsl_program_num, "position");
597         GLint texcoord_attribute_index = glGetAttribLocation(phase->glsl_program_num, "texcoord");
598         if (position_attribute_index != -1) {
599                 phase->attribute_indexes.insert(position_attribute_index);
600         }
601         if (texcoord_attribute_index != -1) {
602                 phase->attribute_indexes.insert(texcoord_attribute_index);
603         }
604
605         // Collect the resulting location numbers for each uniform.
606         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_image2d);
607         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
608         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
609         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
610         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
611         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
612         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
613         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
614         collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
615 }
616
617 // Construct GLSL programs, starting at the given effect and following
618 // the chain from there. We end a program every time we come to an effect
619 // marked as "needs texture bounce", one that is used by multiple other
620 // effects, every time we need to bounce due to output size change
621 // (not all size changes require ending), and of course at the end.
622 //
623 // We follow a quite simple depth-first search from the output, although
624 // without recursing explicitly within each phase.
625 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
626 {
627         if (completed_effects->count(output)) {
628                 return (*completed_effects)[output];
629         }
630
631         Phase *phase = new Phase;
632         phase->output_node = output;
633         phase->is_compute_shader = false;
634         phase->compute_shader_node = nullptr;
635
636         // If the output effect has one-to-one sampling, we try to trace this
637         // status down through the dependency chain. This is important in case
638         // we hit an effect that changes output size (and not sets a virtual
639         // output size); if we have one-to-one sampling, we don't have to break
640         // the phase.
641         output->one_to_one_sampling = output->effect->one_to_one_sampling();
642         output->strong_one_to_one_sampling = output->effect->strong_one_to_one_sampling();
643
644         // Effects that we have yet to calculate, but that we know should
645         // be in the current phase.
646         stack<Node *> effects_todo_this_phase;
647         effects_todo_this_phase.push(output);
648
649         while (!effects_todo_this_phase.empty()) {
650                 Node *node = effects_todo_this_phase.top();
651                 effects_todo_this_phase.pop();
652
653                 assert(node->effect->one_to_one_sampling() >= node->effect->strong_one_to_one_sampling());
654
655                 if (node->effect->needs_mipmaps()) {
656                         node->needs_mipmaps = true;
657                 }
658
659                 // This should currently only happen for effects that are inputs
660                 // (either true inputs or phase outputs). We special-case inputs,
661                 // and then deduplicate phase outputs below.
662                 if (node->effect->num_inputs() == 0) {
663                         if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
664                                 continue;
665                         }
666                 } else {
667                         assert(completed_effects->count(node) == 0);
668                 }
669
670                 phase->effects.push_back(node);
671                 if (node->effect->is_compute_shader()) {
672                         phase->is_compute_shader = true;
673                         phase->compute_shader_node = node;
674                 }
675
676                 // Find all the dependencies of this effect, and add them to the stack.
677                 vector<Node *> deps = node->incoming_links;
678                 assert(node->effect->num_inputs() == deps.size());
679                 for (unsigned i = 0; i < deps.size(); ++i) {
680                         bool start_new_phase = false;
681
682                         if (node->effect->needs_texture_bounce() &&
683                             !deps[i]->effect->is_single_texture() &&
684                             !deps[i]->effect->override_disable_bounce()) {
685                                 start_new_phase = true;
686                         }
687
688                         // Propagate information about needing mipmaps down the chain,
689                         // breaking the phase if we notice an incompatibility.
690                         //
691                         // Note that we cannot do this propagation as a normal pass,
692                         // because it needs information about where the phases end
693                         // (we should not propagate the flag across phases).
694                         if (node->needs_mipmaps) {
695                                 if (deps[i]->effect->num_inputs() == 0) {
696                                         Input *input = static_cast<Input *>(deps[i]->effect);
697                                         start_new_phase |= !input->can_supply_mipmaps();
698                                 } else {
699                                         deps[i]->needs_mipmaps = true;
700                                 }
701                         }
702
703                         if (deps[i]->outgoing_links.size() > 1) {
704                                 if (!deps[i]->effect->is_single_texture()) {
705                                         // More than one effect uses this as the input,
706                                         // and it is not a texture itself.
707                                         // The easiest thing to do (and probably also the safest
708                                         // performance-wise in most cases) is to bounce it to a texture
709                                         // and then let the next passes read from that.
710                                         start_new_phase = true;
711                                 } else {
712                                         assert(deps[i]->effect->num_inputs() == 0);
713
714                                         // For textures, we try to be slightly more clever;
715                                         // if none of our outputs need a bounce, we don't bounce
716                                         // but instead simply use the effect many times.
717                                         //
718                                         // Strictly speaking, we could bounce it for some outputs
719                                         // and use it directly for others, but the processing becomes
720                                         // somewhat simpler if the effect is only used in one such way.
721                                         for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
722                                                 Node *rdep = deps[i]->outgoing_links[j];
723                                                 start_new_phase |= rdep->effect->needs_texture_bounce();
724                                         }
725                                 }
726                         }
727
728                         if (deps[i]->effect->is_compute_shader()) {
729                                 // Only one compute shader per phase; we should have been stopped
730                                 // already due to the fact that compute shaders are not one-to-one.
731                                 assert(!phase->is_compute_shader);
732
733                                 // If all nodes so far are strong one-to-one, we can put them after
734                                 // the compute shader (ie., process them on the output).
735                                 start_new_phase = !node->strong_one_to_one_sampling;
736                         } else if (deps[i]->effect->sets_virtual_output_size()) {
737                                 assert(deps[i]->effect->changes_output_size());
738                                 // If the next effect sets a virtual size to rely on OpenGL's
739                                 // bilinear sampling, we'll really need to break the phase here.
740                                 start_new_phase = true;
741                         } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
742                                 // If the next effect changes size and we don't have one-to-one sampling,
743                                 // we also need to break here.
744                                 start_new_phase = true;
745                         }
746
747                         if (start_new_phase) {
748                                 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
749                         } else {
750                                 effects_todo_this_phase.push(deps[i]);
751
752                                 // Propagate the one-to-one status down through the dependency.
753                                 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
754                                         deps[i]->effect->one_to_one_sampling();
755                                 deps[i]->strong_one_to_one_sampling = node->strong_one_to_one_sampling &&
756                                         deps[i]->effect->strong_one_to_one_sampling();
757                         }
758                 }
759         }
760
761         // No more effects to do this phase. Take all the ones we have,
762         // and create a GLSL program for it.
763         assert(!phase->effects.empty());
764
765         // Deduplicate the inputs, but don't change the ordering e.g. by sorting;
766         // that would be nondeterministic and thus reduce cacheability.
767         // TODO: Make this even more deterministic.
768         vector<Phase *> dedup_inputs;
769         set<Phase *> seen_inputs;
770         for (size_t i = 0; i < phase->inputs.size(); ++i) {
771                 if (seen_inputs.insert(phase->inputs[i]).second) {
772                         dedup_inputs.push_back(phase->inputs[i]);
773                 }
774         }
775         swap(phase->inputs, dedup_inputs);
776
777         // Allocate samplers for each input.
778         phase->input_samplers.resize(phase->inputs.size());
779
780         // We added the effects from the output and back, but we need to output
781         // them in topological sort order in the shader.
782         phase->effects = topological_sort(phase->effects);
783
784         // Figure out if we need mipmaps or not, and if so, tell the inputs that.
785         phase->input_needs_mipmaps = false;
786         for (unsigned i = 0; i < phase->effects.size(); ++i) {
787                 Node *node = phase->effects[i];
788                 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
789         }
790         for (unsigned i = 0; i < phase->effects.size(); ++i) {
791                 Node *node = phase->effects[i];
792                 if (node->effect->num_inputs() == 0) {
793                         Input *input = static_cast<Input *>(node->effect);
794                         assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
795                         CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
796                 }
797         }
798
799         // Tell each node which phase it ended up in, so that the unit test
800         // can check that the phases were split in the right place.
801         // Note that this ignores that effects may be part of multiple phases;
802         // if the unit tests need to test such cases, we'll reconsider.
803         for (unsigned i = 0; i < phase->effects.size(); ++i) {
804                 phase->effects[i]->containing_phase = phase;
805         }
806
807         // Actually make the shader for this phase.
808         compile_glsl_program(phase);
809
810         // Initialize timers.
811         if (movit_timer_queries_supported) {
812                 phase->time_elapsed_ns = 0;
813                 phase->num_measured_iterations = 0;
814         }
815
816         assert(completed_effects->count(output) == 0);
817         completed_effects->insert(make_pair(output, phase));
818         phases.push_back(phase);
819         return phase;
820 }
821
822 void EffectChain::output_dot(const char *filename)
823 {
824         if (movit_debug_level != MOVIT_DEBUG_ON) {
825                 return;
826         }
827
828         FILE *fp = fopen(filename, "w");
829         if (fp == nullptr) {
830                 perror(filename);
831                 exit(1);
832         }
833
834         fprintf(fp, "digraph G {\n");
835         fprintf(fp, "  output [shape=box label=\"(output)\"];\n");
836         for (unsigned i = 0; i < nodes.size(); ++i) {
837                 // Find out which phase this event belongs to.
838                 vector<int> in_phases;
839                 for (unsigned j = 0; j < phases.size(); ++j) {
840                         const Phase* p = phases[j];
841                         if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
842                                 in_phases.push_back(j);
843                         }
844                 }
845
846                 if (in_phases.empty()) {
847                         fprintf(fp, "  n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
848                 } else if (in_phases.size() == 1) {
849                         fprintf(fp, "  n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
850                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
851                                 (in_phases[0] % 8) + 1);
852                 } else {
853                         // If we had new enough Graphviz, style="wedged" would probably be ideal here.
854                         // But alas.
855                         fprintf(fp, "  n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
856                                 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
857                                 (in_phases[0] % 8) + 1);
858                 }
859
860                 char from_node_id[256];
861                 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
862
863                 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
864                         char to_node_id[256];
865                         snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
866
867                         vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
868                         output_dot_edge(fp, from_node_id, to_node_id, labels);
869                 }
870
871                 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
872                         // Output node.
873                         vector<string> labels = get_labels_for_edge(nodes[i], nullptr);
874                         output_dot_edge(fp, from_node_id, "output", labels);
875                 }
876         }
877         fprintf(fp, "}\n");
878
879         fclose(fp);
880 }
881
882 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
883 {
884         vector<string> labels;
885
886         if (to != nullptr && to->effect->needs_texture_bounce()) {
887                 labels.push_back("needs_bounce");
888         }
889         if (from->effect->changes_output_size()) {
890                 labels.push_back("resize");
891         }
892
893         switch (from->output_color_space) {
894         case COLORSPACE_INVALID:
895                 labels.push_back("spc[invalid]");
896                 break;
897         case COLORSPACE_REC_601_525:
898                 labels.push_back("spc[rec601-525]");
899                 break;
900         case COLORSPACE_REC_601_625:
901                 labels.push_back("spc[rec601-625]");
902                 break;
903         default:
904                 break;
905         }
906
907         switch (from->output_gamma_curve) {
908         case GAMMA_INVALID:
909                 labels.push_back("gamma[invalid]");
910                 break;
911         case GAMMA_sRGB:
912                 labels.push_back("gamma[sRGB]");
913                 break;
914         case GAMMA_REC_601:  // and GAMMA_REC_709
915                 labels.push_back("gamma[rec601/709]");
916                 break;
917         default:
918                 break;
919         }
920
921         switch (from->output_alpha_type) {
922         case ALPHA_INVALID:
923                 labels.push_back("alpha[invalid]");
924                 break;
925         case ALPHA_BLANK:
926                 labels.push_back("alpha[blank]");
927                 break;
928         case ALPHA_POSTMULTIPLIED:
929                 labels.push_back("alpha[postmult]");
930                 break;
931         default:
932                 break;
933         }
934
935         return labels;
936 }
937
938 void EffectChain::output_dot_edge(FILE *fp,
939                                   const string &from_node_id,
940                                   const string &to_node_id,
941                                   const vector<string> &labels)
942 {
943         if (labels.empty()) {
944                 fprintf(fp, "  %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
945         } else {
946                 string label = labels[0];
947                 for (unsigned k = 1; k < labels.size(); ++k) {
948                         label += ", " + labels[k];
949                 }
950                 fprintf(fp, "  %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
951         }
952 }
953
954 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
955 {
956         unsigned scaled_width, scaled_height;
957
958         if (float(width) * aspect_denom >= float(height) * aspect_nom) {
959                 // Same aspect, or W/H > aspect (image is wider than the frame).
960                 // In either case, keep width, and adjust height.
961                 scaled_width = width;
962                 scaled_height = lrintf(width * aspect_denom / aspect_nom);
963         } else {
964                 // W/H < aspect (image is taller than the frame), so keep height,
965                 // and adjust width.
966                 scaled_width = lrintf(height * aspect_nom / aspect_denom);
967                 scaled_height = height;
968         }
969
970         // We should be consistently larger or smaller then the existing choice,
971         // since we have the same aspect.
972         assert(!(scaled_width < *output_width && scaled_height > *output_height));
973         assert(!(scaled_height < *output_height && scaled_width > *output_width));
974
975         if (scaled_width >= *output_width && scaled_height >= *output_height) {
976                 *output_width = scaled_width;
977                 *output_height = scaled_height;
978         }
979 }
980
981 // Propagate input texture sizes throughout, and inform effects downstream.
982 // (Like a lot of other code, we depend on effects being in topological order.)
983 void EffectChain::inform_input_sizes(Phase *phase)
984 {
985         // All effects that have a defined size (inputs and RTT inputs)
986         // get that. Reset all others.
987         for (unsigned i = 0; i < phase->effects.size(); ++i) {
988                 Node *node = phase->effects[i];
989                 if (node->effect->num_inputs() == 0) {
990                         Input *input = static_cast<Input *>(node->effect);
991                         node->output_width = input->get_width();
992                         node->output_height = input->get_height();
993                         assert(node->output_width != 0);
994                         assert(node->output_height != 0);
995                 } else {
996                         node->output_width = node->output_height = 0;
997                 }
998         }
999         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1000                 Phase *input = phase->inputs[i];
1001                 input->output_node->output_width = input->virtual_output_width;
1002                 input->output_node->output_height = input->virtual_output_height;
1003                 assert(input->output_node->output_width != 0);
1004                 assert(input->output_node->output_height != 0);
1005         }
1006
1007         // Now propagate from the inputs towards the end, and inform as we go.
1008         // The rules are simple:
1009         //
1010         //   1. Don't touch effects that already have given sizes (ie., inputs
1011         //      or effects that change the output size).
1012         //   2. If all of your inputs have the same size, that will be your output size.
1013         //   3. Otherwise, your output size is 0x0.
1014         for (unsigned i = 0; i < phase->effects.size(); ++i) {
1015                 Node *node = phase->effects[i];
1016                 if (node->effect->num_inputs() == 0) {
1017                         continue;
1018                 }
1019                 unsigned this_output_width = 0;
1020                 unsigned this_output_height = 0;
1021                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1022                         Node *input = node->incoming_links[j];
1023                         node->effect->inform_input_size(j, input->output_width, input->output_height);
1024                         if (j == 0) {
1025                                 this_output_width = input->output_width;
1026                                 this_output_height = input->output_height;
1027                         } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
1028                                 // Inputs disagree.
1029                                 this_output_width = 0;
1030                                 this_output_height = 0;
1031                         }
1032                 }
1033                 if (node->effect->changes_output_size()) {
1034                         // We cannot call get_output_size() before we've done inform_input_size()
1035                         // on all inputs.
1036                         unsigned real_width, real_height;
1037                         node->effect->get_output_size(&real_width, &real_height,
1038                                                       &node->output_width, &node->output_height);
1039                         assert(node->effect->sets_virtual_output_size() ||
1040                                (real_width == node->output_width &&
1041                                 real_height == node->output_height));
1042                 } else {
1043                         node->output_width = this_output_width;
1044                         node->output_height = this_output_height;
1045                 }
1046         }
1047 }
1048
1049 // Note: You should call inform_input_sizes() before this, as the last effect's
1050 // desired output size might change based on the inputs.
1051 void EffectChain::find_output_size(Phase *phase)
1052 {
1053         Node *output_node = phase->is_compute_shader ? phase->compute_shader_node : phase->effects.back();
1054
1055         // If the last effect explicitly sets an output size, use that.
1056         if (output_node->effect->changes_output_size()) {
1057                 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
1058                                                      &phase->virtual_output_width, &phase->virtual_output_height);
1059                 assert(output_node->effect->sets_virtual_output_size() ||
1060                        (phase->output_width == phase->virtual_output_width &&
1061                         phase->output_height == phase->virtual_output_height));
1062                 return;
1063         }
1064
1065         // If all effects have the same size, use that.
1066         unsigned output_width = 0, output_height = 0;
1067         bool all_inputs_same_size = true;
1068
1069         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1070                 Phase *input = phase->inputs[i];
1071                 assert(input->output_width != 0);
1072                 assert(input->output_height != 0);
1073                 if (output_width == 0 && output_height == 0) {
1074                         output_width = input->virtual_output_width;
1075                         output_height = input->virtual_output_height;
1076                 } else if (output_width != input->virtual_output_width ||
1077                            output_height != input->virtual_output_height) {
1078                         all_inputs_same_size = false;
1079                 }
1080         }
1081         for (unsigned i = 0; i < phase->effects.size(); ++i) {
1082                 Effect *effect = phase->effects[i]->effect;
1083                 if (effect->num_inputs() != 0) {
1084                         continue;
1085                 }
1086
1087                 Input *input = static_cast<Input *>(effect);
1088                 if (output_width == 0 && output_height == 0) {
1089                         output_width = input->get_width();
1090                         output_height = input->get_height();
1091                 } else if (output_width != input->get_width() ||
1092                            output_height != input->get_height()) {
1093                         all_inputs_same_size = false;
1094                 }
1095         }
1096
1097         if (all_inputs_same_size) {
1098                 assert(output_width != 0);
1099                 assert(output_height != 0);
1100                 phase->virtual_output_width = phase->output_width = output_width;
1101                 phase->virtual_output_height = phase->output_height = output_height;
1102                 return;
1103         }
1104
1105         // If not, fit all the inputs into the current aspect, and select the largest one. 
1106         output_width = 0;
1107         output_height = 0;
1108         for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1109                 Phase *input = phase->inputs[i];
1110                 assert(input->output_width != 0);
1111                 assert(input->output_height != 0);
1112                 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
1113         }
1114         for (unsigned i = 0; i < phase->effects.size(); ++i) {
1115                 Effect *effect = phase->effects[i]->effect;
1116                 if (effect->num_inputs() != 0) {
1117                         continue;
1118                 }
1119
1120                 Input *input = static_cast<Input *>(effect);
1121                 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
1122         }
1123         assert(output_width != 0);
1124         assert(output_height != 0);
1125         phase->virtual_output_width = phase->output_width = output_width;
1126         phase->virtual_output_height = phase->output_height = output_height;
1127 }
1128
1129 void EffectChain::sort_all_nodes_topologically()
1130 {
1131         nodes = topological_sort(nodes);
1132 }
1133
1134 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
1135 {
1136         set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
1137         vector<Node *> sorted_list;
1138         for (unsigned i = 0; i < nodes.size(); ++i) {
1139                 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
1140         }
1141         reverse(sorted_list.begin(), sorted_list.end());
1142         return sorted_list;
1143 }
1144
1145 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
1146 {
1147         if (nodes_left_to_visit->count(node) == 0) {
1148                 return;
1149         }
1150         nodes_left_to_visit->erase(node);
1151         for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
1152                 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
1153         }
1154         sorted_list->push_back(node);
1155 }
1156
1157 void EffectChain::find_color_spaces_for_inputs()
1158 {
1159         for (unsigned i = 0; i < nodes.size(); ++i) {
1160                 Node *node = nodes[i];
1161                 if (node->disabled) {
1162                         continue;
1163                 }
1164                 if (node->incoming_links.size() == 0) {
1165                         Input *input = static_cast<Input *>(node->effect);
1166                         node->output_color_space = input->get_color_space();
1167                         node->output_gamma_curve = input->get_gamma_curve();
1168
1169                         Effect::AlphaHandling alpha_handling = input->alpha_handling();
1170                         switch (alpha_handling) {
1171                         case Effect::OUTPUT_BLANK_ALPHA:
1172                                 node->output_alpha_type = ALPHA_BLANK;
1173                                 break;
1174                         case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
1175                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1176                                 break;
1177                         case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
1178                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1179                                 break;
1180                         case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
1181                         case Effect::DONT_CARE_ALPHA_TYPE:
1182                         default:
1183                                 assert(false);
1184                         }
1185
1186                         if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
1187                                 assert(node->output_gamma_curve == GAMMA_LINEAR);
1188                         }
1189                 }
1190         }
1191 }
1192
1193 // Propagate gamma and color space information as far as we can in the graph.
1194 // The rules are simple: Anything where all the inputs agree, get that as
1195 // output as well. Anything else keeps having *_INVALID.
1196 void EffectChain::propagate_gamma_and_color_space()
1197 {
1198         // We depend on going through the nodes in order.
1199         sort_all_nodes_topologically();
1200
1201         for (unsigned i = 0; i < nodes.size(); ++i) {
1202                 Node *node = nodes[i];
1203                 if (node->disabled) {
1204                         continue;
1205                 }
1206                 assert(node->incoming_links.size() == node->effect->num_inputs());
1207                 if (node->incoming_links.size() == 0) {
1208                         assert(node->output_color_space != COLORSPACE_INVALID);
1209                         assert(node->output_gamma_curve != GAMMA_INVALID);
1210                         continue;
1211                 }
1212
1213                 Colorspace color_space = node->incoming_links[0]->output_color_space;
1214                 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1215                 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1216                         if (node->incoming_links[j]->output_color_space != color_space) {
1217                                 color_space = COLORSPACE_INVALID;
1218                         }
1219                         if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1220                                 gamma_curve = GAMMA_INVALID;
1221                         }
1222                 }
1223
1224                 // The conversion effects already have their outputs set correctly,
1225                 // so leave them alone.
1226                 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1227                         node->output_color_space = color_space;
1228                 }               
1229                 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1230                     node->effect->effect_type_id() != "GammaExpansionEffect") {
1231                         node->output_gamma_curve = gamma_curve;
1232                 }               
1233         }
1234 }
1235
1236 // Propagate alpha information as far as we can in the graph.
1237 // Similar to propagate_gamma_and_color_space().
1238 void EffectChain::propagate_alpha()
1239 {
1240         // We depend on going through the nodes in order.
1241         sort_all_nodes_topologically();
1242
1243         for (unsigned i = 0; i < nodes.size(); ++i) {
1244                 Node *node = nodes[i];
1245                 if (node->disabled) {
1246                         continue;
1247                 }
1248                 assert(node->incoming_links.size() == node->effect->num_inputs());
1249                 if (node->incoming_links.size() == 0) {
1250                         assert(node->output_alpha_type != ALPHA_INVALID);
1251                         continue;
1252                 }
1253
1254                 // The alpha multiplication/division effects are special cases.
1255                 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1256                         assert(node->incoming_links.size() == 1);
1257                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1258                         node->output_alpha_type = ALPHA_PREMULTIPLIED;
1259                         continue;
1260                 }
1261                 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1262                         assert(node->incoming_links.size() == 1);
1263                         assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1264                         node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1265                         continue;
1266                 }
1267
1268                 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1269                 // because they are the only one that _need_ postmultiplied alpha.
1270                 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1271                     node->effect->effect_type_id() == "GammaExpansionEffect") {
1272                         assert(node->incoming_links.size() == 1);
1273                         if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1274                                 node->output_alpha_type = ALPHA_BLANK;
1275                         } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1276                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1277                         } else {
1278                                 node->output_alpha_type = ALPHA_INVALID;
1279                         }
1280                         continue;
1281                 }
1282
1283                 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1284                 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1285                 // taken care of above. Rationale: Even if you could imagine
1286                 // e.g. an effect that took in an image and set alpha=1.0
1287                 // unconditionally, it wouldn't make any sense to have it as
1288                 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1289                 // got its input pre- or postmultiplied, so it wouldn't know
1290                 // whether to divide away the old alpha or not.
1291                 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1292                 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1293                        alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1294                        alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1295
1296                 // If the node has multiple inputs, check that they are all valid and
1297                 // the same.
1298                 bool any_invalid = false;
1299                 bool any_premultiplied = false;
1300                 bool any_postmultiplied = false;
1301
1302                 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1303                         switch (node->incoming_links[j]->output_alpha_type) {
1304                         case ALPHA_INVALID:
1305                                 any_invalid = true;
1306                                 break;
1307                         case ALPHA_BLANK:
1308                                 // Blank is good as both pre- and postmultiplied alpha,
1309                                 // so just ignore it.
1310                                 break;
1311                         case ALPHA_PREMULTIPLIED:
1312                                 any_premultiplied = true;
1313                                 break;
1314                         case ALPHA_POSTMULTIPLIED:
1315                                 any_postmultiplied = true;
1316                                 break;
1317                         default:
1318                                 assert(false);
1319                         }
1320                 }
1321
1322                 if (any_invalid) {
1323                         node->output_alpha_type = ALPHA_INVALID;
1324                         continue;
1325                 }
1326
1327                 // Inputs must be of the same type.
1328                 if (any_premultiplied && any_postmultiplied) {
1329                         node->output_alpha_type = ALPHA_INVALID;
1330                         continue;
1331                 }
1332
1333                 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1334                     alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1335                         // This combination (requiring premultiplied alpha, but _not_ requiring
1336                         // linear light) is illegal, since the combination of premultiplied alpha
1337                         // and nonlinear inputs is meaningless.
1338                         assert(node->effect->needs_linear_light());
1339
1340                         // If the effect has asked for premultiplied alpha, check that it has got it.
1341                         if (any_postmultiplied) {
1342                                 node->output_alpha_type = ALPHA_INVALID;
1343                         } else if (!any_premultiplied &&
1344                                    alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1345                                 // Blank input alpha, and the effect preserves blank alpha.
1346                                 node->output_alpha_type = ALPHA_BLANK;
1347                         } else {
1348                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1349                         }
1350                 } else {
1351                         // OK, all inputs are the same, and this effect is not going
1352                         // to change it.
1353                         assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1354                         if (any_premultiplied) {
1355                                 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1356                         } else if (any_postmultiplied) {
1357                                 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1358                         } else {
1359                                 node->output_alpha_type = ALPHA_BLANK;
1360                         }
1361                 }
1362         }
1363 }
1364
1365 bool EffectChain::node_needs_colorspace_fix(Node *node)
1366 {
1367         if (node->disabled) {
1368                 return false;
1369         }
1370         if (node->effect->num_inputs() == 0) {
1371                 return false;
1372         }
1373
1374         // propagate_gamma_and_color_space() has already set our output
1375         // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1376         if (node->output_color_space == COLORSPACE_INVALID) {
1377                 return true;
1378         }
1379         return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1380 }
1381
1382 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1383 // the graph. Our strategy is not always optimal, but quite simple:
1384 // Find an effect that's as early as possible where the inputs are of
1385 // unacceptable colorspaces (that is, either different, or, if the effect only
1386 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1387 // propagate the information anew, and repeat until there are no more such
1388 // effects.
1389 void EffectChain::fix_internal_color_spaces()
1390 {
1391         unsigned colorspace_propagation_pass = 0;
1392         bool found_any;
1393         do {
1394                 found_any = false;
1395                 for (unsigned i = 0; i < nodes.size(); ++i) {
1396                         Node *node = nodes[i];
1397                         if (!node_needs_colorspace_fix(node)) {
1398                                 continue;
1399                         }
1400
1401                         // Go through each input that is not sRGB, and insert
1402                         // a colorspace conversion after it.
1403                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1404                                 Node *input = node->incoming_links[j];
1405                                 assert(input->output_color_space != COLORSPACE_INVALID);
1406                                 if (input->output_color_space == COLORSPACE_sRGB) {
1407                                         continue;
1408                                 }
1409                                 Node *conversion = add_node(new ColorspaceConversionEffect());
1410                                 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1411                                 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1412                                 conversion->output_color_space = COLORSPACE_sRGB;
1413                                 replace_sender(input, conversion);
1414                                 connect_nodes(input, conversion);
1415                         }
1416
1417                         // Re-sort topologically, and propagate the new information.
1418                         propagate_gamma_and_color_space();
1419                         
1420                         found_any = true;
1421                         break;
1422                 }
1423         
1424                 char filename[256];
1425                 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1426                 output_dot(filename);
1427                 assert(colorspace_propagation_pass < 100);
1428         } while (found_any);
1429
1430         for (unsigned i = 0; i < nodes.size(); ++i) {
1431                 Node *node = nodes[i];
1432                 if (node->disabled) {
1433                         continue;
1434                 }
1435                 assert(node->output_color_space != COLORSPACE_INVALID);
1436         }
1437 }
1438
1439 bool EffectChain::node_needs_alpha_fix(Node *node)
1440 {
1441         if (node->disabled) {
1442                 return false;
1443         }
1444
1445         // propagate_alpha() has already set our output to ALPHA_INVALID if the
1446         // inputs differ or we are otherwise in mismatch, so we can rely on that.
1447         return (node->output_alpha_type == ALPHA_INVALID);
1448 }
1449
1450 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1451 // the graph. Similar to fix_internal_color_spaces().
1452 void EffectChain::fix_internal_alpha(unsigned step)
1453 {
1454         unsigned alpha_propagation_pass = 0;
1455         bool found_any;
1456         do {
1457                 found_any = false;
1458                 for (unsigned i = 0; i < nodes.size(); ++i) {
1459                         Node *node = nodes[i];
1460                         if (!node_needs_alpha_fix(node)) {
1461                                 continue;
1462                         }
1463
1464                         // If we need to fix up GammaExpansionEffect, then clearly something
1465                         // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1466                         // is meaningless.
1467                         assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1468
1469                         AlphaType desired_type = ALPHA_PREMULTIPLIED;
1470
1471                         // GammaCompressionEffect is special; it needs postmultiplied alpha.
1472                         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1473                                 assert(node->incoming_links.size() == 1);
1474                                 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1475                                 desired_type = ALPHA_POSTMULTIPLIED;
1476                         }
1477
1478                         // Go through each input that is not premultiplied alpha, and insert
1479                         // a conversion before it.
1480                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1481                                 Node *input = node->incoming_links[j];
1482                                 assert(input->output_alpha_type != ALPHA_INVALID);
1483                                 if (input->output_alpha_type == desired_type ||
1484                                     input->output_alpha_type == ALPHA_BLANK) {
1485                                         continue;
1486                                 }
1487                                 Node *conversion;
1488                                 if (desired_type == ALPHA_PREMULTIPLIED) {
1489                                         conversion = add_node(new AlphaMultiplicationEffect());
1490                                 } else {
1491                                         conversion = add_node(new AlphaDivisionEffect());
1492                                 }
1493                                 conversion->output_alpha_type = desired_type;
1494                                 replace_sender(input, conversion);
1495                                 connect_nodes(input, conversion);
1496                         }
1497
1498                         // Re-sort topologically, and propagate the new information.
1499                         propagate_gamma_and_color_space();
1500                         propagate_alpha();
1501                         
1502                         found_any = true;
1503                         break;
1504                 }
1505         
1506                 char filename[256];
1507                 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1508                 output_dot(filename);
1509                 assert(alpha_propagation_pass < 100);
1510         } while (found_any);
1511
1512         for (unsigned i = 0; i < nodes.size(); ++i) {
1513                 Node *node = nodes[i];
1514                 if (node->disabled) {
1515                         continue;
1516                 }
1517                 assert(node->output_alpha_type != ALPHA_INVALID);
1518         }
1519 }
1520
1521 // Make so that the output is in the desired color space.
1522 void EffectChain::fix_output_color_space()
1523 {
1524         Node *output = find_output_node();
1525         if (output->output_color_space != output_format.color_space) {
1526                 Node *conversion = add_node(new ColorspaceConversionEffect());
1527                 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1528                 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1529                 conversion->output_color_space = output_format.color_space;
1530                 connect_nodes(output, conversion);
1531                 propagate_alpha();
1532                 propagate_gamma_and_color_space();
1533         }
1534 }
1535
1536 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1537 void EffectChain::fix_output_alpha()
1538 {
1539         Node *output = find_output_node();
1540         assert(output->output_alpha_type != ALPHA_INVALID);
1541         if (output->output_alpha_type == ALPHA_BLANK) {
1542                 // No alpha output, so we don't care.
1543                 return;
1544         }
1545         if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1546             output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1547                 Node *conversion = add_node(new AlphaDivisionEffect());
1548                 connect_nodes(output, conversion);
1549                 propagate_alpha();
1550                 propagate_gamma_and_color_space();
1551         }
1552         if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1553             output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1554                 Node *conversion = add_node(new AlphaMultiplicationEffect());
1555                 connect_nodes(output, conversion);
1556                 propagate_alpha();
1557                 propagate_gamma_and_color_space();
1558         }
1559 }
1560
1561 bool EffectChain::node_needs_gamma_fix(Node *node)
1562 {
1563         if (node->disabled) {
1564                 return false;
1565         }
1566
1567         // Small hack since the output is not an explicit node:
1568         // If we are the last node and our output is in the wrong
1569         // space compared to EffectChain's output, we need to fix it.
1570         // This will only take us to linear, but fix_output_gamma()
1571         // will come and take us to the desired output gamma
1572         // if it is needed.
1573         //
1574         // This needs to be before everything else, since it could
1575         // even apply to inputs (if they are the only effect).
1576         if (node->outgoing_links.empty() &&
1577             node->output_gamma_curve != output_format.gamma_curve &&
1578             node->output_gamma_curve != GAMMA_LINEAR) {
1579                 return true;
1580         }
1581
1582         if (node->effect->num_inputs() == 0) {
1583                 return false;
1584         }
1585
1586         // propagate_gamma_and_color_space() has already set our output
1587         // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1588         // except for GammaCompressionEffect.
1589         if (node->output_gamma_curve == GAMMA_INVALID) {
1590                 return true;
1591         }
1592         if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1593                 assert(node->incoming_links.size() == 1);
1594                 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1595         }
1596
1597         return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1598 }
1599
1600 // Very similar to fix_internal_color_spaces(), but for gamma.
1601 // There is one difference, though; before we start adding conversion nodes,
1602 // we see if we can get anything out of asking the sources to deliver
1603 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1604 // does that part, while fix_internal_gamma_by_inserting_nodes()
1605 // inserts nodes as needed afterwards.
1606 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1607 {
1608         unsigned gamma_propagation_pass = 0;
1609         bool found_any;
1610         do {
1611                 found_any = false;
1612                 for (unsigned i = 0; i < nodes.size(); ++i) {
1613                         Node *node = nodes[i];
1614                         if (!node_needs_gamma_fix(node)) {
1615                                 continue;
1616                         }
1617
1618                         // See if all inputs can give us linear gamma. If not, leave it.
1619                         vector<Node *> nonlinear_inputs;
1620                         find_all_nonlinear_inputs(node, &nonlinear_inputs);
1621                         assert(!nonlinear_inputs.empty());
1622
1623                         bool all_ok = true;
1624                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1625                                 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1626                                 all_ok &= input->can_output_linear_gamma();
1627                         }
1628
1629                         if (!all_ok) {
1630                                 continue;
1631                         }
1632
1633                         for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1634                                 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1635                                 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1636                         }
1637
1638                         // Re-sort topologically, and propagate the new information.
1639                         propagate_gamma_and_color_space();
1640                         
1641                         found_any = true;
1642                         break;
1643                 }
1644         
1645                 char filename[256];
1646                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1647                 output_dot(filename);
1648                 assert(gamma_propagation_pass < 100);
1649         } while (found_any);
1650 }
1651
1652 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1653 {
1654         unsigned gamma_propagation_pass = 0;
1655         bool found_any;
1656         do {
1657                 found_any = false;
1658                 for (unsigned i = 0; i < nodes.size(); ++i) {
1659                         Node *node = nodes[i];
1660                         if (!node_needs_gamma_fix(node)) {
1661                                 continue;
1662                         }
1663
1664                         // Special case: We could be an input and still be asked to
1665                         // fix our gamma; if so, we should be the only node
1666                         // (as node_needs_gamma_fix() would only return true in
1667                         // for an input in that case). That means we should insert
1668                         // a conversion node _after_ ourselves.
1669                         if (node->incoming_links.empty()) {
1670                                 assert(node->outgoing_links.empty());
1671                                 Node *conversion = add_node(new GammaExpansionEffect());
1672                                 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1673                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1674                                 connect_nodes(node, conversion);
1675                         }
1676
1677                         // If not, go through each input that is not linear gamma,
1678                         // and insert a gamma conversion after it.
1679                         for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1680                                 Node *input = node->incoming_links[j];
1681                                 assert(input->output_gamma_curve != GAMMA_INVALID);
1682                                 if (input->output_gamma_curve == GAMMA_LINEAR) {
1683                                         continue;
1684                                 }
1685                                 Node *conversion = add_node(new GammaExpansionEffect());
1686                                 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1687                                 conversion->output_gamma_curve = GAMMA_LINEAR;
1688                                 replace_sender(input, conversion);
1689                                 connect_nodes(input, conversion);
1690                         }
1691
1692                         // Re-sort topologically, and propagate the new information.
1693                         propagate_alpha();
1694                         propagate_gamma_and_color_space();
1695                         
1696                         found_any = true;
1697                         break;
1698                 }
1699         
1700                 char filename[256];
1701                 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1702                 output_dot(filename);
1703                 assert(gamma_propagation_pass < 100);
1704         } while (found_any);
1705
1706         for (unsigned i = 0; i < nodes.size(); ++i) {
1707                 Node *node = nodes[i];
1708                 if (node->disabled) {
1709                         continue;
1710                 }
1711                 assert(node->output_gamma_curve != GAMMA_INVALID);
1712         }
1713 }
1714
1715 // Make so that the output is in the desired gamma.
1716 // Note that this assumes linear input gamma, so it might create the need
1717 // for another pass of fix_internal_gamma().
1718 void EffectChain::fix_output_gamma()
1719 {
1720         Node *output = find_output_node();
1721         if (output->output_gamma_curve != output_format.gamma_curve) {
1722                 Node *conversion = add_node(new GammaCompressionEffect());
1723                 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1724                 conversion->output_gamma_curve = output_format.gamma_curve;
1725                 connect_nodes(output, conversion);
1726         }
1727 }
1728
1729 // If the user has requested Y'CbCr output, we need to do this conversion
1730 // _after_ GammaCompressionEffect etc., but before dither (see below).
1731 // This is because Y'CbCr, with the exception of a special optional mode
1732 // in Rec. 2020 (which we currently don't support), is defined to work on
1733 // gamma-encoded data.
1734 void EffectChain::add_ycbcr_conversion_if_needed()
1735 {
1736         assert(output_color_rgba || num_output_color_ycbcr > 0);
1737         if (num_output_color_ycbcr == 0) {
1738                 return;
1739         }
1740         Node *output = find_output_node();
1741         ycbcr_conversion_effect_node = add_node(new YCbCrConversionEffect(output_ycbcr_format, output_ycbcr_type));
1742         connect_nodes(output, ycbcr_conversion_effect_node);
1743 }
1744         
1745 // If the user has requested dither, add a DitherEffect right at the end
1746 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1747 // since dither is about the only effect that can _not_ be done in linear space.
1748 void EffectChain::add_dither_if_needed()
1749 {
1750         if (num_dither_bits == 0) {
1751                 return;
1752         }
1753         Node *output = find_output_node();
1754         Node *dither = add_node(new DitherEffect());
1755         CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1756         connect_nodes(output, dither);
1757
1758         dither_effect = dither->effect;
1759 }
1760
1761 // Compute shaders can't output to the framebuffer, so if the last
1762 // phase ends in a compute shader, add a dummy phase at the end that
1763 // only blits directly from the temporary texture.
1764 //
1765 // TODO: Add an API for rendering directly to textures, for the cases
1766 // where we're only rendering to an FBO anyway.
1767 void EffectChain::add_dummy_effect_if_needed()
1768 {
1769         Node *output = find_output_node();
1770
1771         // See if the last effect that's not strong one-to-one is a compute shader.
1772         Node *last_effect = output;
1773         while (last_effect->effect->num_inputs() == 1 &&
1774                last_effect->effect->strong_one_to_one_sampling()) {
1775                 last_effect = last_effect->incoming_links[0];
1776         }
1777         if (last_effect->effect->is_compute_shader()) {
1778                 Node *dummy = add_node(new ComputeShaderOutputDisplayEffect());
1779                 connect_nodes(output, dummy);
1780                 has_dummy_effect = true;
1781         }
1782 }
1783
1784 // Find the output node. This is, simply, one that has no outgoing links.
1785 // If there are multiple ones, the graph is malformed (we do not support
1786 // multiple outputs right now).
1787 Node *EffectChain::find_output_node()
1788 {
1789         vector<Node *> output_nodes;
1790         for (unsigned i = 0; i < nodes.size(); ++i) {
1791                 Node *node = nodes[i];
1792                 if (node->disabled) {
1793                         continue;
1794                 }
1795                 if (node->outgoing_links.empty()) {
1796                         output_nodes.push_back(node);
1797                 }
1798         }
1799         assert(output_nodes.size() == 1);
1800         return output_nodes[0];
1801 }
1802
1803 void EffectChain::finalize()
1804 {
1805         // Output the graph as it is before we do any conversions on it.
1806         output_dot("step0-start.dot");
1807
1808         // Give each effect in turn a chance to rewrite its own part of the graph.
1809         // Note that if more effects are added as part of this, they will be
1810         // picked up as part of the same for loop, since they are added at the end.
1811         for (unsigned i = 0; i < nodes.size(); ++i) {
1812                 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1813         }
1814         output_dot("step1-rewritten.dot");
1815
1816         find_color_spaces_for_inputs();
1817         output_dot("step2-input-colorspace.dot");
1818
1819         propagate_alpha();
1820         output_dot("step3-propagated-alpha.dot");
1821
1822         propagate_gamma_and_color_space();
1823         output_dot("step4-propagated-all.dot");
1824
1825         fix_internal_color_spaces();
1826         fix_internal_alpha(6);
1827         fix_output_color_space();
1828         output_dot("step7-output-colorspacefix.dot");
1829         fix_output_alpha();
1830         output_dot("step8-output-alphafix.dot");
1831
1832         // Note that we need to fix gamma after colorspace conversion,
1833         // because colorspace conversions might create needs for gamma conversions.
1834         // Also, we need to run an extra pass of fix_internal_gamma() after 
1835         // fixing the output gamma, as we only have conversions to/from linear,
1836         // and fix_internal_alpha() since GammaCompressionEffect needs
1837         // postmultiplied input.
1838         fix_internal_gamma_by_asking_inputs(9);
1839         fix_internal_gamma_by_inserting_nodes(10);
1840         fix_output_gamma();
1841         output_dot("step11-output-gammafix.dot");
1842         propagate_alpha();
1843         output_dot("step12-output-alpha-propagated.dot");
1844         fix_internal_alpha(13);
1845         output_dot("step14-output-alpha-fixed.dot");
1846         fix_internal_gamma_by_asking_inputs(15);
1847         fix_internal_gamma_by_inserting_nodes(16);
1848
1849         output_dot("step17-before-ycbcr.dot");
1850         add_ycbcr_conversion_if_needed();
1851
1852         output_dot("step18-before-dither.dot");
1853         add_dither_if_needed();
1854
1855         output_dot("step19-before-dummy-effect.dot");
1856         add_dummy_effect_if_needed();
1857
1858         output_dot("step20-final.dot");
1859         
1860         // Construct all needed GLSL programs, starting at the output.
1861         // We need to keep track of which effects have already been computed,
1862         // as an effect with multiple users could otherwise be calculated
1863         // multiple times.
1864         map<Node *, Phase *> completed_effects;
1865         construct_phase(find_output_node(), &completed_effects);
1866
1867         output_dot("step21-split-to-phases.dot");
1868
1869         assert(phases[0]->inputs.empty());
1870         
1871         finalized = true;
1872 }
1873
1874 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1875 {
1876         // Save original viewport.
1877         GLuint x = 0, y = 0;
1878
1879         if (width == 0 && height == 0) {
1880                 GLint viewport[4];
1881                 glGetIntegerv(GL_VIEWPORT, viewport);
1882                 x = viewport[0];
1883                 y = viewport[1];
1884                 width = viewport[2];
1885                 height = viewport[3];
1886         }
1887
1888         render(dest_fbo, {}, x, y, width, height);
1889 }
1890
1891 void EffectChain::render_to_texture(const vector<DestinationTexture> &destinations, unsigned width, unsigned height)
1892 {
1893         assert(finalized);
1894         assert(!destinations.empty());
1895
1896         if (!has_dummy_effect) {
1897                 // We don't end in a compute shader, so there's nothing specific for us to do.
1898                 // Create an FBO for this set of textures, and just render to that.
1899                 GLuint texnums[4] = { 0, 0, 0, 0 };
1900                 for (unsigned i = 0; i < destinations.size() && i < 4; ++i) {
1901                         texnums[i] = destinations[i].texnum;
1902                 }
1903                 GLuint dest_fbo = resource_pool->create_fbo(texnums[0], texnums[1], texnums[2], texnums[3]);
1904                 render(dest_fbo, {}, 0, 0, width, height);
1905                 resource_pool->release_fbo(dest_fbo);
1906         } else {
1907                 render((GLuint)-1, destinations, 0, 0, width, height);
1908         }
1909 }
1910
1911 void EffectChain::render(GLuint dest_fbo, const vector<DestinationTexture> &destinations, unsigned x, unsigned y, unsigned width, unsigned height)
1912 {
1913         assert(finalized);
1914         assert(destinations.size() <= 1);
1915
1916         // This needs to be set anew, in case we are coming from a different context
1917         // from when we initialized.
1918         check_error();
1919         glDisable(GL_DITHER);
1920         check_error();
1921
1922         const bool final_srgb = glIsEnabled(GL_FRAMEBUFFER_SRGB);
1923         check_error();
1924         bool current_srgb = final_srgb;
1925
1926         // Basic state.
1927         check_error();
1928         glDisable(GL_BLEND);
1929         check_error();
1930         glDisable(GL_DEPTH_TEST);
1931         check_error();
1932         glDepthMask(GL_FALSE);
1933         check_error();
1934
1935         set<Phase *> generated_mipmaps;
1936
1937         // We keep one texture per output, but only for as long as we actually have any
1938         // phases that need it as an input. (We don't make any effort to reorder phases
1939         // to minimize the number of textures in play, as register allocation can be
1940         // complicated and we rarely have much to gain, since our graphs are typically
1941         // pretty linear.)
1942         map<Phase *, GLuint> output_textures;
1943         map<Phase *, int> ref_counts;
1944         for (Phase *phase : phases) {
1945                 for (Phase *input : phase->inputs) {
1946                         ++ref_counts[input];
1947                 }
1948         }
1949
1950         size_t num_phases = phases.size();
1951         if (destinations.empty()) {
1952                 assert(dest_fbo != (GLuint)-1);
1953         } else {
1954                 assert(has_dummy_effect);
1955                 assert(x == 0);
1956                 assert(y == 0);
1957                 assert(num_phases >= 2);
1958                 assert(!phases.back()->is_compute_shader);
1959                 assert(phases.back()->effects.size() == 1);
1960                 assert(phases.back()->effects[0]->effect->effect_type_id() == "ComputeShaderOutputDisplayEffect");
1961
1962                 // We are rendering to a set of textures, so we can run the compute shader
1963                 // directly and skip the dummy phase.
1964                 --num_phases;
1965         }
1966
1967         for (unsigned phase_num = 0; phase_num < num_phases; ++phase_num) {
1968                 Phase *phase = phases[phase_num];
1969
1970                 if (do_phase_timing) {
1971                         GLuint timer_query_object;
1972                         if (phase->timer_query_objects_free.empty()) {
1973                                 glGenQueries(1, &timer_query_object);
1974                         } else {
1975                                 timer_query_object = phase->timer_query_objects_free.front();
1976                                 phase->timer_query_objects_free.pop_front();
1977                         }
1978                         glBeginQuery(GL_TIME_ELAPSED, timer_query_object);
1979                         phase->timer_query_objects_running.push_back(timer_query_object);
1980                 }
1981                 bool last_phase = (phase_num == num_phases - 1);
1982                 if (phase_num == num_phases - 1) {
1983                         // Last phase goes to the output the user specified.
1984                         if (!phase->is_compute_shader) {
1985                                 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1986                                 check_error();
1987                                 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1988                                 assert(status == GL_FRAMEBUFFER_COMPLETE);
1989                                 glViewport(x, y, width, height);
1990                         }
1991                         if (dither_effect != nullptr) {
1992                                 CHECK(dither_effect->set_int("output_width", width));
1993                                 CHECK(dither_effect->set_int("output_height", height));
1994                         }
1995                 }
1996
1997                 // Enable sRGB rendering for intermediates in case we are
1998                 // rendering to an sRGB format.
1999                 // TODO: Support this for compute shaders.
2000                 bool needs_srgb = last_phase ? final_srgb : true;
2001                 if (needs_srgb && !current_srgb) {
2002                         glEnable(GL_FRAMEBUFFER_SRGB);
2003                         check_error();
2004                         current_srgb = true;
2005                 } else if (!needs_srgb && current_srgb) {
2006                         glDisable(GL_FRAMEBUFFER_SRGB);
2007                         check_error();
2008                         current_srgb = true;
2009                 }
2010
2011                 // Find a texture for this phase.
2012                 inform_input_sizes(phase);
2013                 find_output_size(phase);
2014                 vector<DestinationTexture> phase_destinations;
2015                 if (!last_phase) {
2016                         GLuint tex_num = resource_pool->create_2d_texture(intermediate_format, phase->output_width, phase->output_height);
2017                         output_textures.insert(make_pair(phase, tex_num));
2018                         phase_destinations.push_back(DestinationTexture{ tex_num, intermediate_format });
2019
2020                         // The output texture needs to have valid state to be written to by a compute shader.
2021                         glActiveTexture(GL_TEXTURE0);
2022                         check_error();
2023                         glBindTexture(GL_TEXTURE_2D, tex_num);
2024                         check_error();
2025                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2026                         check_error();
2027                 } else if (phase->is_compute_shader) {
2028                         assert(!destinations.empty());
2029                         phase_destinations = destinations;
2030                 }
2031
2032                 execute_phase(phase, output_textures, phase_destinations, &generated_mipmaps);
2033                 if (do_phase_timing) {
2034                         glEndQuery(GL_TIME_ELAPSED);
2035                 }
2036
2037                 // Drop any input textures we don't need anymore.
2038                 for (Phase *input : phase->inputs) {
2039                         assert(ref_counts[input] > 0);
2040                         if (--ref_counts[input] == 0) {
2041                                 resource_pool->release_2d_texture(output_textures[input]);
2042                                 output_textures.erase(input);
2043                         }
2044                 }
2045         }
2046
2047         for (const auto &phase_and_texnum : output_textures) {
2048                 resource_pool->release_2d_texture(phase_and_texnum.second);
2049         }
2050
2051         glBindFramebuffer(GL_FRAMEBUFFER, 0);
2052         check_error();
2053         glUseProgram(0);
2054         check_error();
2055
2056         glBindBuffer(GL_ARRAY_BUFFER, 0);
2057         check_error();
2058         glBindVertexArray(0);
2059         check_error();
2060
2061         if (do_phase_timing) {
2062                 // Get back the timer queries.
2063                 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2064                         Phase *phase = phases[phase_num];
2065                         for (auto timer_it = phase->timer_query_objects_running.cbegin();
2066                              timer_it != phase->timer_query_objects_running.cend(); ) {
2067                                 GLint timer_query_object = *timer_it;
2068                                 GLint available;
2069                                 glGetQueryObjectiv(timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
2070                                 if (available) {
2071                                         GLuint64 time_elapsed;
2072                                         glGetQueryObjectui64v(timer_query_object, GL_QUERY_RESULT, &time_elapsed);
2073                                         phase->time_elapsed_ns += time_elapsed;
2074                                         ++phase->num_measured_iterations;
2075                                         phase->timer_query_objects_free.push_back(timer_query_object);
2076                                         phase->timer_query_objects_running.erase(timer_it++);
2077                                 } else {
2078                                         ++timer_it;
2079                                 }
2080                         }
2081                 }
2082         }
2083 }
2084
2085 void EffectChain::enable_phase_timing(bool enable)
2086 {
2087         if (enable) {
2088                 assert(movit_timer_queries_supported);
2089         }
2090         this->do_phase_timing = enable;
2091 }
2092
2093 void EffectChain::reset_phase_timing()
2094 {
2095         for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2096                 Phase *phase = phases[phase_num];
2097                 phase->time_elapsed_ns = 0;
2098                 phase->num_measured_iterations = 0;
2099         }
2100 }
2101
2102 void EffectChain::print_phase_timing()
2103 {
2104         double total_time_ms = 0.0;
2105         for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2106                 Phase *phase = phases[phase_num];
2107                 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
2108                 printf("Phase %d: %5.1f ms  [", phase_num, avg_time_ms);
2109                 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
2110                         if (effect_num != 0) {
2111                                 printf(", ");
2112                         }
2113                         printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
2114                 }
2115                 printf("]\n");
2116                 total_time_ms += avg_time_ms;
2117         }
2118         printf("Total:   %5.1f ms\n", total_time_ms);
2119 }
2120
2121 void EffectChain::execute_phase(Phase *phase,
2122                                 const map<Phase *, GLuint> &output_textures,
2123                                 const std::vector<DestinationTexture> &destinations,
2124                                 set<Phase *> *generated_mipmaps)
2125 {
2126         // Set up RTT inputs for this phase.
2127         for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
2128                 glActiveTexture(GL_TEXTURE0 + sampler);
2129                 Phase *input = phase->inputs[sampler];
2130                 input->output_node->bound_sampler_num = sampler;
2131                 const auto it = output_textures.find(input);
2132                 assert(it != output_textures.end());
2133                 glBindTexture(GL_TEXTURE_2D, it->second);
2134                 check_error();
2135                 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
2136                         glGenerateMipmap(GL_TEXTURE_2D);
2137                         check_error();
2138                         generated_mipmaps->insert(input);
2139                 }
2140                 setup_rtt_sampler(sampler, phase->input_needs_mipmaps);
2141                 phase->input_samplers[sampler] = sampler;  // Bind the sampler to the right uniform.
2142         }
2143
2144         GLuint instance_program_num = resource_pool->use_glsl_program(phase->glsl_program_num);
2145         check_error();
2146
2147         // And now the output.
2148         GLuint fbo = 0;
2149         if (phase->is_compute_shader) {
2150                 assert(!destinations.empty());
2151
2152                 // This is currently the only place where we use image units,
2153                 // so we can always start at 0. TODO: Support multiple destinations.
2154                 phase->outbuf_image_unit = 0;
2155                 glBindImageTexture(phase->outbuf_image_unit, destinations[0].texnum, 0, GL_FALSE, 0, GL_WRITE_ONLY, destinations[0].format);
2156                 check_error();
2157                 phase->inv_output_size.x = 1.0f / phase->output_width;
2158                 phase->inv_output_size.y = 1.0f / phase->output_height;
2159                 phase->output_texcoord_adjust.x = 0.5f / phase->output_width;
2160                 phase->output_texcoord_adjust.y = 0.5f / phase->output_height;
2161         } else if (!destinations.empty()) {
2162                 assert(destinations.size() == 1);
2163                 fbo = resource_pool->create_fbo(destinations[0].texnum);
2164                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
2165                 glViewport(0, 0, phase->output_width, phase->output_height);
2166         }
2167
2168         // Give the required parameters to all the effects.
2169         unsigned sampler_num = phase->inputs.size();
2170         for (unsigned i = 0; i < phase->effects.size(); ++i) {
2171                 Node *node = phase->effects[i];
2172                 unsigned old_sampler_num = sampler_num;
2173                 node->effect->set_gl_state(instance_program_num, phase->effect_ids[node], &sampler_num);
2174                 check_error();
2175
2176                 if (node->effect->is_single_texture()) {
2177                         assert(sampler_num - old_sampler_num == 1);
2178                         node->bound_sampler_num = old_sampler_num;
2179                 } else {
2180                         node->bound_sampler_num = -1;
2181                 }
2182         }
2183
2184         if (phase->is_compute_shader) {
2185                 unsigned x, y, z;
2186                 phase->compute_shader_node->effect->get_compute_dimensions(phase->output_width, phase->output_height, &x, &y, &z);
2187
2188                 // Uniforms need to come after set_gl_state() _and_ get_compute_dimensions(),
2189                 // since they can be updated from there.
2190                 setup_uniforms(phase);
2191                 glDispatchCompute(x, y, z);
2192                 check_error();
2193                 glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_TEXTURE_UPDATE_BARRIER_BIT);
2194                 check_error();
2195         } else {
2196                 // Uniforms need to come after set_gl_state(), since they can be updated
2197                 // from there.
2198                 setup_uniforms(phase);
2199
2200                 // Bind the vertex data.
2201                 GLuint vao = resource_pool->create_vec2_vao(phase->attribute_indexes, vbo);
2202                 glBindVertexArray(vao);
2203
2204                 glDrawArrays(GL_TRIANGLES, 0, 3);
2205                 check_error();
2206
2207                 resource_pool->release_vec2_vao(vao);
2208         }
2209         
2210         for (unsigned i = 0; i < phase->effects.size(); ++i) {
2211                 Node *node = phase->effects[i];
2212                 node->effect->clear_gl_state();
2213         }
2214
2215         resource_pool->unuse_glsl_program(instance_program_num);
2216
2217         if (fbo != 0) {
2218                 resource_pool->release_fbo(fbo);
2219         }
2220 }
2221
2222 void EffectChain::setup_uniforms(Phase *phase)
2223 {
2224         // TODO: Use UBO blocks.
2225         for (size_t i = 0; i < phase->uniforms_image2d.size(); ++i) {
2226                 const Uniform<int> &uniform = phase->uniforms_image2d[i];
2227                 if (uniform.location != -1) {
2228                         glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2229                 }
2230         }
2231         for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
2232                 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
2233                 if (uniform.location != -1) {
2234                         glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2235                 }
2236         }
2237         for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
2238                 const Uniform<bool> &uniform = phase->uniforms_bool[i];
2239                 assert(uniform.num_values == 1);
2240                 if (uniform.location != -1) {
2241                         glUniform1i(uniform.location, *uniform.value);
2242                 }
2243         }
2244         for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
2245                 const Uniform<int> &uniform = phase->uniforms_int[i];
2246                 if (uniform.location != -1) {
2247                         glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2248                 }
2249         }
2250         for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
2251                 const Uniform<float> &uniform = phase->uniforms_float[i];
2252                 if (uniform.location != -1) {
2253                         glUniform1fv(uniform.location, uniform.num_values, uniform.value);
2254                 }
2255         }
2256         for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
2257                 const Uniform<float> &uniform = phase->uniforms_vec2[i];
2258                 if (uniform.location != -1) {
2259                         glUniform2fv(uniform.location, uniform.num_values, uniform.value);
2260                 }
2261         }
2262         for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
2263                 const Uniform<float> &uniform = phase->uniforms_vec3[i];
2264                 if (uniform.location != -1) {
2265                         glUniform3fv(uniform.location, uniform.num_values, uniform.value);
2266                 }
2267         }
2268         for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
2269                 const Uniform<float> &uniform = phase->uniforms_vec4[i];
2270                 if (uniform.location != -1) {
2271                         glUniform4fv(uniform.location, uniform.num_values, uniform.value);
2272                 }
2273         }
2274         for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
2275                 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
2276                 assert(uniform.num_values == 1);
2277                 if (uniform.location != -1) {
2278                         // Convert to float (GLSL has no double matrices).
2279                         float matrixf[9];
2280                         for (unsigned y = 0; y < 3; ++y) {
2281                                 for (unsigned x = 0; x < 3; ++x) {
2282                                         matrixf[y + x * 3] = (*uniform.value)(y, x);
2283                                 }
2284                         }
2285                         glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
2286                 }
2287         }
2288 }
2289
2290 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
2291 {
2292         glActiveTexture(GL_TEXTURE0 + sampler_num);
2293         check_error();
2294         if (use_mipmaps) {
2295                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
2296                 check_error();
2297         } else {
2298                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2299                 check_error();
2300         }
2301         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2302         check_error();
2303         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2304         check_error();
2305 }
2306
2307 }  // namespace movit