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