15 #include "alpha_division_effect.h"
16 #include "alpha_multiplication_effect.h"
17 #include "colorspace_conversion_effect.h"
18 #include "dither_effect.h"
20 #include "effect_chain.h"
21 #include "effect_util.h"
22 #include "gamma_compression_effect.h"
23 #include "gamma_expansion_effect.h"
26 #include "resource_pool.h"
28 #include "ycbcr_conversion_effect.h"
30 using namespace Eigen;
35 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
36 : aspect_nom(aspect_nom),
37 aspect_denom(aspect_denom),
38 output_color_rgba(false),
39 output_color_ycbcr(false),
41 ycbcr_conversion_effect_node(NULL),
42 intermediate_format(GL_RGBA16F),
43 intermediate_transformation(NO_FRAMEBUFFER_TRANSFORMATION),
45 output_origin(OUTPUT_ORIGIN_BOTTOM_LEFT),
47 resource_pool(resource_pool),
48 do_phase_timing(false) {
49 if (resource_pool == NULL) {
50 this->resource_pool = new ResourcePool();
51 owns_resource_pool = true;
53 owns_resource_pool = false;
56 // Generate a VBO with some data in (shared position and texture coordinate data).
62 vbo = generate_vbo(2, GL_FLOAT, sizeof(vertices), vertices);
65 EffectChain::~EffectChain()
67 for (unsigned i = 0; i < nodes.size(); ++i) {
68 delete nodes[i]->effect;
71 for (unsigned i = 0; i < phases.size(); ++i) {
72 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
75 if (owns_resource_pool) {
78 glDeleteBuffers(1, &vbo);
82 Input *EffectChain::add_input(Input *input)
85 inputs.push_back(input);
90 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
93 assert(!output_color_rgba);
94 output_format = format;
95 output_alpha_format = alpha_format;
96 output_color_rgba = true;
99 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
100 const YCbCrFormat &ycbcr_format, YCbCrOutputSplitting output_splitting)
103 assert(!output_color_ycbcr);
104 output_format = format;
105 output_alpha_format = alpha_format;
106 output_color_ycbcr = true;
107 output_ycbcr_format = ycbcr_format;
108 output_ycbcr_splitting = output_splitting;
110 assert(ycbcr_format.chroma_subsampling_x == 1);
111 assert(ycbcr_format.chroma_subsampling_y == 1);
114 void EffectChain::change_ycbcr_output_format(const YCbCrFormat &ycbcr_format)
116 assert(output_color_ycbcr);
117 assert(output_ycbcr_format.chroma_subsampling_x == ycbcr_format.chroma_subsampling_x);
118 assert(output_ycbcr_format.chroma_subsampling_y == ycbcr_format.chroma_subsampling_y);
119 assert(fabs(output_ycbcr_format.cb_x_position - ycbcr_format.cb_x_position) < 1e-3);
120 assert(fabs(output_ycbcr_format.cb_y_position - ycbcr_format.cb_y_position) < 1e-3);
121 assert(fabs(output_ycbcr_format.cr_x_position - ycbcr_format.cr_x_position) < 1e-3);
122 assert(fabs(output_ycbcr_format.cr_y_position - ycbcr_format.cr_y_position) < 1e-3);
124 output_ycbcr_format = ycbcr_format;
126 YCbCrConversionEffect *effect = (YCbCrConversionEffect *)(ycbcr_conversion_effect_node->effect);
127 effect->change_output_format(ycbcr_format);
131 Node *EffectChain::add_node(Effect *effect)
133 for (unsigned i = 0; i < nodes.size(); ++i) {
134 assert(nodes[i]->effect != effect);
137 Node *node = new Node;
138 node->effect = effect;
139 node->disabled = false;
140 node->output_color_space = COLORSPACE_INVALID;
141 node->output_gamma_curve = GAMMA_INVALID;
142 node->output_alpha_type = ALPHA_INVALID;
143 node->needs_mipmaps = false;
144 node->one_to_one_sampling = false;
146 nodes.push_back(node);
147 node_map[effect] = node;
148 effect->inform_added(this);
152 void EffectChain::connect_nodes(Node *sender, Node *receiver)
154 sender->outgoing_links.push_back(receiver);
155 receiver->incoming_links.push_back(sender);
158 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
160 new_receiver->incoming_links = old_receiver->incoming_links;
161 old_receiver->incoming_links.clear();
163 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
164 Node *sender = new_receiver->incoming_links[i];
165 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
166 if (sender->outgoing_links[j] == old_receiver) {
167 sender->outgoing_links[j] = new_receiver;
173 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
175 new_sender->outgoing_links = old_sender->outgoing_links;
176 old_sender->outgoing_links.clear();
178 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
179 Node *receiver = new_sender->outgoing_links[i];
180 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
181 if (receiver->incoming_links[j] == old_sender) {
182 receiver->incoming_links[j] = new_sender;
188 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
190 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
191 if (sender->outgoing_links[i] == receiver) {
192 sender->outgoing_links[i] = middle;
193 middle->incoming_links.push_back(sender);
196 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
197 if (receiver->incoming_links[i] == sender) {
198 receiver->incoming_links[i] = middle;
199 middle->outgoing_links.push_back(receiver);
203 assert(middle->incoming_links.size() == middle->effect->num_inputs());
206 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
208 assert(node->effect->needs_texture_bounce());
209 assert(input_num < node->incoming_links.size());
210 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
211 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
212 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
215 GLenum EffectChain::has_input_sampler(Node *node, unsigned input_num) const
217 assert(input_num < node->incoming_links.size());
218 return node->incoming_links[input_num]->bound_sampler_num >= 0 &&
219 node->incoming_links[input_num]->bound_sampler_num < 8;
222 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
224 if (node->output_gamma_curve == GAMMA_LINEAR &&
225 node->effect->effect_type_id() != "GammaCompressionEffect") {
228 if (node->effect->num_inputs() == 0) {
229 nonlinear_inputs->push_back(node);
231 assert(node->effect->num_inputs() == node->incoming_links.size());
232 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
233 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
238 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
241 assert(inputs.size() == effect->num_inputs());
242 Node *node = add_node(effect);
243 for (unsigned i = 0; i < inputs.size(); ++i) {
244 assert(node_map.count(inputs[i]) != 0);
245 connect_nodes(node_map[inputs[i]], node);
250 // ESSL doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
251 string replace_prefix(const string &text, const string &prefix)
256 while (start < text.size()) {
257 size_t pos = text.find("PREFIX(", start);
258 if (pos == string::npos) {
259 output.append(text.substr(start, string::npos));
263 output.append(text.substr(start, pos - start));
264 output.append(prefix);
267 pos += strlen("PREFIX(");
269 // Output stuff until we find the matching ), which we then eat.
271 size_t end_arg_pos = pos;
272 while (end_arg_pos < text.size()) {
273 if (text[end_arg_pos] == '(') {
275 } else if (text[end_arg_pos] == ')') {
283 output.append(text.substr(pos, end_arg_pos - pos));
294 void extract_uniform_declarations(const vector<Uniform<T> > &effect_uniforms,
295 const string &type_specifier,
296 const string &effect_id,
297 vector<Uniform<T> > *phase_uniforms,
300 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
301 phase_uniforms->push_back(effect_uniforms[i]);
302 phase_uniforms->back().prefix = effect_id;
304 *glsl_string += string("uniform ") + type_specifier + " " + effect_id
305 + "_" + effect_uniforms[i].name + ";\n";
310 void extract_uniform_array_declarations(const vector<Uniform<T> > &effect_uniforms,
311 const string &type_specifier,
312 const string &effect_id,
313 vector<Uniform<T> > *phase_uniforms,
316 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
317 phase_uniforms->push_back(effect_uniforms[i]);
318 phase_uniforms->back().prefix = effect_id;
321 snprintf(buf, sizeof(buf), "uniform %s %s_%s[%d];\n",
322 type_specifier.c_str(), effect_id.c_str(),
323 effect_uniforms[i].name.c_str(),
324 int(effect_uniforms[i].num_values));
330 void collect_uniform_locations(GLuint glsl_program_num, vector<Uniform<T> > *phase_uniforms)
332 for (unsigned i = 0; i < phase_uniforms->size(); ++i) {
333 Uniform<T> &uniform = (*phase_uniforms)[i];
334 uniform.location = get_uniform_location(glsl_program_num, uniform.prefix, uniform.name);
340 void EffectChain::compile_glsl_program(Phase *phase)
342 string frag_shader_header = read_version_dependent_file("header", "frag");
343 string frag_shader = "";
345 // Create functions and uniforms for all the texture inputs that we need.
346 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
347 Node *input = phase->inputs[i]->output_node;
349 sprintf(effect_id, "in%u", i);
350 phase->effect_ids.insert(make_pair(input, effect_id));
352 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
353 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
354 frag_shader += "\tvec4 tmp = tex2D(tex_" + string(effect_id) + ", tc);\n";
356 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
357 phase->inputs[i]->output_node->output_gamma_curve == GAMMA_LINEAR) {
358 frag_shader += "\ttmp.rgb *= tmp.rgb;\n";
361 frag_shader += "\treturn tmp;\n";
362 frag_shader += "}\n";
365 Uniform<int> uniform;
366 uniform.name = effect_id;
367 uniform.value = &phase->input_samplers[i];
368 uniform.prefix = "tex";
369 uniform.num_values = 1;
370 uniform.location = -1;
371 phase->uniforms_sampler2d.push_back(uniform);
374 // Give each effect in the phase its own ID.
375 for (unsigned i = 0; i < phase->effects.size(); ++i) {
376 Node *node = phase->effects[i];
378 sprintf(effect_id, "eff%u", i);
379 phase->effect_ids.insert(make_pair(node, effect_id));
382 for (unsigned i = 0; i < phase->effects.size(); ++i) {
383 Node *node = phase->effects[i];
384 const string effect_id = phase->effect_ids[node];
385 if (node->incoming_links.size() == 1) {
386 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
388 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
390 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
396 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
397 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
398 frag_shader += "#undef PREFIX\n";
399 frag_shader += "#undef FUNCNAME\n";
400 if (node->incoming_links.size() == 1) {
401 frag_shader += "#undef INPUT\n";
403 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
405 sprintf(buf, "#undef INPUT%d\n", j + 1);
411 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
413 // If we're the last phase, add the right #defines for Y'CbCr multi-output as needed.
414 vector<string> frag_shader_outputs; // In order.
415 if (phase->output_node->outgoing_links.empty() && output_color_ycbcr) {
416 switch (output_ycbcr_splitting) {
417 case YCBCR_OUTPUT_INTERLEAVED:
419 frag_shader_outputs.push_back("FragColor");
421 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
422 frag_shader += "#define YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
423 frag_shader_outputs.push_back("Y");
424 frag_shader_outputs.push_back("Chroma");
426 case YCBCR_OUTPUT_PLANAR:
427 frag_shader += "#define YCBCR_OUTPUT_PLANAR 1\n";
428 frag_shader_outputs.push_back("Y");
429 frag_shader_outputs.push_back("Cb");
430 frag_shader_outputs.push_back("Cr");
436 if (output_color_rgba) {
437 // Note: Needs to come in the header, because not only the
438 // output needs to see it (YCbCrConversionEffect and DitherEffect
440 frag_shader_header += "#define YCBCR_ALSO_OUTPUT_RGBA 1\n";
441 frag_shader_outputs.push_back("RGBA");
445 // If we're bouncing to a temporary texture, signal transformation if desired.
446 if (!phase->output_node->outgoing_links.empty()) {
447 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
448 phase->output_node->output_gamma_curve == GAMMA_LINEAR) {
449 frag_shader += "#define SQUARE_ROOT_TRANSFORMATION 1\n";
453 frag_shader.append(read_file("footer.frag"));
455 // Collect uniforms from all effects and output them. Note that this needs
456 // to happen after output_fragment_shader(), even though the uniforms come
457 // before in the output source, since output_fragment_shader() is allowed
458 // to register new uniforms (e.g. arrays that are of unknown length until
459 // finalization time).
460 // TODO: Make a uniform block for platforms that support it.
461 string frag_shader_uniforms = "";
462 for (unsigned i = 0; i < phase->effects.size(); ++i) {
463 Node *node = phase->effects[i];
464 Effect *effect = node->effect;
465 const string effect_id = phase->effect_ids[node];
466 extract_uniform_declarations(effect->uniforms_sampler2d, "sampler2D", effect_id, &phase->uniforms_sampler2d, &frag_shader_uniforms);
467 extract_uniform_declarations(effect->uniforms_bool, "bool", effect_id, &phase->uniforms_bool, &frag_shader_uniforms);
468 extract_uniform_declarations(effect->uniforms_int, "int", effect_id, &phase->uniforms_int, &frag_shader_uniforms);
469 extract_uniform_declarations(effect->uniforms_float, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
470 extract_uniform_declarations(effect->uniforms_vec2, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
471 extract_uniform_declarations(effect->uniforms_vec3, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
472 extract_uniform_declarations(effect->uniforms_vec4, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
473 extract_uniform_array_declarations(effect->uniforms_float_array, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
474 extract_uniform_array_declarations(effect->uniforms_vec2_array, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
475 extract_uniform_array_declarations(effect->uniforms_vec3_array, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
476 extract_uniform_array_declarations(effect->uniforms_vec4_array, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
477 extract_uniform_declarations(effect->uniforms_mat3, "mat3", effect_id, &phase->uniforms_mat3, &frag_shader_uniforms);
480 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
482 string vert_shader = read_version_dependent_file("vs", "vert");
484 // If we're the last phase and need to flip the picture to compensate for
485 // the origin, tell the vertex shader so.
486 if (phase->output_node->outgoing_links.empty() && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
487 const string needle = "#define FLIP_ORIGIN 0";
488 size_t pos = vert_shader.find(needle);
489 assert(pos != string::npos);
491 vert_shader[pos + needle.size() - 1] = '1';
494 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader, frag_shader_outputs);
495 GLint position_attribute_index = glGetAttribLocation(phase->glsl_program_num, "position");
496 GLint texcoord_attribute_index = glGetAttribLocation(phase->glsl_program_num, "texcoord");
497 if (position_attribute_index != -1) {
498 phase->attribute_indexes.insert(position_attribute_index);
500 if (texcoord_attribute_index != -1) {
501 phase->attribute_indexes.insert(texcoord_attribute_index);
504 // Collect the resulting location numbers for each uniform.
505 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
506 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
507 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
508 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
509 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
510 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
511 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
512 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
515 // Construct GLSL programs, starting at the given effect and following
516 // the chain from there. We end a program every time we come to an effect
517 // marked as "needs texture bounce", one that is used by multiple other
518 // effects, every time we need to bounce due to output size change
519 // (not all size changes require ending), and of course at the end.
521 // We follow a quite simple depth-first search from the output, although
522 // without recursing explicitly within each phase.
523 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
525 if (completed_effects->count(output)) {
526 return (*completed_effects)[output];
529 Phase *phase = new Phase;
530 phase->output_node = output;
532 // If the output effect has one-to-one sampling, we try to trace this
533 // status down through the dependency chain. This is important in case
534 // we hit an effect that changes output size (and not sets a virtual
535 // output size); if we have one-to-one sampling, we don't have to break
537 output->one_to_one_sampling = output->effect->one_to_one_sampling();
539 // Effects that we have yet to calculate, but that we know should
540 // be in the current phase.
541 stack<Node *> effects_todo_this_phase;
542 effects_todo_this_phase.push(output);
544 while (!effects_todo_this_phase.empty()) {
545 Node *node = effects_todo_this_phase.top();
546 effects_todo_this_phase.pop();
548 if (node->effect->needs_mipmaps()) {
549 node->needs_mipmaps = true;
552 // This should currently only happen for effects that are inputs
553 // (either true inputs or phase outputs). We special-case inputs,
554 // and then deduplicate phase outputs below.
555 if (node->effect->num_inputs() == 0) {
556 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
560 assert(completed_effects->count(node) == 0);
563 phase->effects.push_back(node);
565 // Find all the dependencies of this effect, and add them to the stack.
566 vector<Node *> deps = node->incoming_links;
567 assert(node->effect->num_inputs() == deps.size());
568 for (unsigned i = 0; i < deps.size(); ++i) {
569 bool start_new_phase = false;
571 if (node->effect->needs_texture_bounce() &&
572 !deps[i]->effect->is_single_texture() &&
573 !deps[i]->effect->override_disable_bounce()) {
574 start_new_phase = true;
577 // Propagate information about needing mipmaps down the chain,
578 // breaking the phase if we notice an incompatibility.
580 // Note that we cannot do this propagation as a normal pass,
581 // because it needs information about where the phases end
582 // (we should not propagate the flag across phases).
583 if (node->needs_mipmaps) {
584 if (deps[i]->effect->num_inputs() == 0) {
585 Input *input = static_cast<Input *>(deps[i]->effect);
586 start_new_phase |= !input->can_supply_mipmaps();
588 deps[i]->needs_mipmaps = true;
592 if (deps[i]->outgoing_links.size() > 1) {
593 if (!deps[i]->effect->is_single_texture()) {
594 // More than one effect uses this as the input,
595 // and it is not a texture itself.
596 // The easiest thing to do (and probably also the safest
597 // performance-wise in most cases) is to bounce it to a texture
598 // and then let the next passes read from that.
599 start_new_phase = true;
601 assert(deps[i]->effect->num_inputs() == 0);
603 // For textures, we try to be slightly more clever;
604 // if none of our outputs need a bounce, we don't bounce
605 // but instead simply use the effect many times.
607 // Strictly speaking, we could bounce it for some outputs
608 // and use it directly for others, but the processing becomes
609 // somewhat simpler if the effect is only used in one such way.
610 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
611 Node *rdep = deps[i]->outgoing_links[j];
612 start_new_phase |= rdep->effect->needs_texture_bounce();
617 if (deps[i]->effect->sets_virtual_output_size()) {
618 assert(deps[i]->effect->changes_output_size());
619 // If the next effect sets a virtual size to rely on OpenGL's
620 // bilinear sampling, we'll really need to break the phase here.
621 start_new_phase = true;
622 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
623 // If the next effect changes size and we don't have one-to-one sampling,
624 // we also need to break here.
625 start_new_phase = true;
628 if (start_new_phase) {
629 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
631 effects_todo_this_phase.push(deps[i]);
633 // Propagate the one-to-one status down through the dependency.
634 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
635 deps[i]->effect->one_to_one_sampling();
640 // No more effects to do this phase. Take all the ones we have,
641 // and create a GLSL program for it.
642 assert(!phase->effects.empty());
644 // Deduplicate the inputs, but don't change the ordering e.g. by sorting;
645 // that would be nondeterministic and thus reduce cacheability.
646 // TODO: Make this even more deterministic.
647 vector<Phase *> dedup_inputs;
648 set<Phase *> seen_inputs;
649 for (size_t i = 0; i < phase->inputs.size(); ++i) {
650 if (seen_inputs.insert(phase->inputs[i]).second) {
651 dedup_inputs.push_back(phase->inputs[i]);
654 swap(phase->inputs, dedup_inputs);
656 // Allocate samplers for each input.
657 phase->input_samplers.resize(phase->inputs.size());
659 // We added the effects from the output and back, but we need to output
660 // them in topological sort order in the shader.
661 phase->effects = topological_sort(phase->effects);
663 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
664 phase->input_needs_mipmaps = false;
665 for (unsigned i = 0; i < phase->effects.size(); ++i) {
666 Node *node = phase->effects[i];
667 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
669 for (unsigned i = 0; i < phase->effects.size(); ++i) {
670 Node *node = phase->effects[i];
671 if (node->effect->num_inputs() == 0) {
672 Input *input = static_cast<Input *>(node->effect);
673 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
674 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
678 // Tell each node which phase it ended up in, so that the unit test
679 // can check that the phases were split in the right place.
680 // Note that this ignores that effects may be part of multiple phases;
681 // if the unit tests need to test such cases, we'll reconsider.
682 for (unsigned i = 0; i < phase->effects.size(); ++i) {
683 phase->effects[i]->containing_phase = phase;
686 // Actually make the shader for this phase.
687 compile_glsl_program(phase);
689 // Initialize timers.
690 if (movit_timer_queries_supported) {
691 phase->time_elapsed_ns = 0;
692 phase->num_measured_iterations = 0;
695 assert(completed_effects->count(output) == 0);
696 completed_effects->insert(make_pair(output, phase));
697 phases.push_back(phase);
701 void EffectChain::output_dot(const char *filename)
703 if (movit_debug_level != MOVIT_DEBUG_ON) {
707 FILE *fp = fopen(filename, "w");
713 fprintf(fp, "digraph G {\n");
714 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
715 for (unsigned i = 0; i < nodes.size(); ++i) {
716 // Find out which phase this event belongs to.
717 vector<int> in_phases;
718 for (unsigned j = 0; j < phases.size(); ++j) {
719 const Phase* p = phases[j];
720 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
721 in_phases.push_back(j);
725 if (in_phases.empty()) {
726 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
727 } else if (in_phases.size() == 1) {
728 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
729 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
730 (in_phases[0] % 8) + 1);
732 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
734 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
735 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
736 (in_phases[0] % 8) + 1);
739 char from_node_id[256];
740 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
742 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
743 char to_node_id[256];
744 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
746 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
747 output_dot_edge(fp, from_node_id, to_node_id, labels);
750 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
752 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
753 output_dot_edge(fp, from_node_id, "output", labels);
761 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
763 vector<string> labels;
765 if (to != NULL && to->effect->needs_texture_bounce()) {
766 labels.push_back("needs_bounce");
768 if (from->effect->changes_output_size()) {
769 labels.push_back("resize");
772 switch (from->output_color_space) {
773 case COLORSPACE_INVALID:
774 labels.push_back("spc[invalid]");
776 case COLORSPACE_REC_601_525:
777 labels.push_back("spc[rec601-525]");
779 case COLORSPACE_REC_601_625:
780 labels.push_back("spc[rec601-625]");
786 switch (from->output_gamma_curve) {
788 labels.push_back("gamma[invalid]");
791 labels.push_back("gamma[sRGB]");
793 case GAMMA_REC_601: // and GAMMA_REC_709
794 labels.push_back("gamma[rec601/709]");
800 switch (from->output_alpha_type) {
802 labels.push_back("alpha[invalid]");
805 labels.push_back("alpha[blank]");
807 case ALPHA_POSTMULTIPLIED:
808 labels.push_back("alpha[postmult]");
817 void EffectChain::output_dot_edge(FILE *fp,
818 const string &from_node_id,
819 const string &to_node_id,
820 const vector<string> &labels)
822 if (labels.empty()) {
823 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
825 string label = labels[0];
826 for (unsigned k = 1; k < labels.size(); ++k) {
827 label += ", " + labels[k];
829 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
833 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
835 unsigned scaled_width, scaled_height;
837 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
838 // Same aspect, or W/H > aspect (image is wider than the frame).
839 // In either case, keep width, and adjust height.
840 scaled_width = width;
841 scaled_height = lrintf(width * aspect_denom / aspect_nom);
843 // W/H < aspect (image is taller than the frame), so keep height,
845 scaled_width = lrintf(height * aspect_nom / aspect_denom);
846 scaled_height = height;
849 // We should be consistently larger or smaller then the existing choice,
850 // since we have the same aspect.
851 assert(!(scaled_width < *output_width && scaled_height > *output_height));
852 assert(!(scaled_height < *output_height && scaled_width > *output_width));
854 if (scaled_width >= *output_width && scaled_height >= *output_height) {
855 *output_width = scaled_width;
856 *output_height = scaled_height;
860 // Propagate input texture sizes throughout, and inform effects downstream.
861 // (Like a lot of other code, we depend on effects being in topological order.)
862 void EffectChain::inform_input_sizes(Phase *phase)
864 // All effects that have a defined size (inputs and RTT inputs)
865 // get that. Reset all others.
866 for (unsigned i = 0; i < phase->effects.size(); ++i) {
867 Node *node = phase->effects[i];
868 if (node->effect->num_inputs() == 0) {
869 Input *input = static_cast<Input *>(node->effect);
870 node->output_width = input->get_width();
871 node->output_height = input->get_height();
872 assert(node->output_width != 0);
873 assert(node->output_height != 0);
875 node->output_width = node->output_height = 0;
878 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
879 Phase *input = phase->inputs[i];
880 input->output_node->output_width = input->virtual_output_width;
881 input->output_node->output_height = input->virtual_output_height;
882 assert(input->output_node->output_width != 0);
883 assert(input->output_node->output_height != 0);
886 // Now propagate from the inputs towards the end, and inform as we go.
887 // The rules are simple:
889 // 1. Don't touch effects that already have given sizes (ie., inputs
890 // or effects that change the output size).
891 // 2. If all of your inputs have the same size, that will be your output size.
892 // 3. Otherwise, your output size is 0x0.
893 for (unsigned i = 0; i < phase->effects.size(); ++i) {
894 Node *node = phase->effects[i];
895 if (node->effect->num_inputs() == 0) {
898 unsigned this_output_width = 0;
899 unsigned this_output_height = 0;
900 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
901 Node *input = node->incoming_links[j];
902 node->effect->inform_input_size(j, input->output_width, input->output_height);
904 this_output_width = input->output_width;
905 this_output_height = input->output_height;
906 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
908 this_output_width = 0;
909 this_output_height = 0;
912 if (node->effect->changes_output_size()) {
913 // We cannot call get_output_size() before we've done inform_input_size()
915 unsigned real_width, real_height;
916 node->effect->get_output_size(&real_width, &real_height,
917 &node->output_width, &node->output_height);
918 assert(node->effect->sets_virtual_output_size() ||
919 (real_width == node->output_width &&
920 real_height == node->output_height));
922 node->output_width = this_output_width;
923 node->output_height = this_output_height;
928 // Note: You should call inform_input_sizes() before this, as the last effect's
929 // desired output size might change based on the inputs.
930 void EffectChain::find_output_size(Phase *phase)
932 Node *output_node = phase->effects.back();
934 // If the last effect explicitly sets an output size, use that.
935 if (output_node->effect->changes_output_size()) {
936 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
937 &phase->virtual_output_width, &phase->virtual_output_height);
938 assert(output_node->effect->sets_virtual_output_size() ||
939 (phase->output_width == phase->virtual_output_width &&
940 phase->output_height == phase->virtual_output_height));
944 // If all effects have the same size, use that.
945 unsigned output_width = 0, output_height = 0;
946 bool all_inputs_same_size = true;
948 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
949 Phase *input = phase->inputs[i];
950 assert(input->output_width != 0);
951 assert(input->output_height != 0);
952 if (output_width == 0 && output_height == 0) {
953 output_width = input->virtual_output_width;
954 output_height = input->virtual_output_height;
955 } else if (output_width != input->virtual_output_width ||
956 output_height != input->virtual_output_height) {
957 all_inputs_same_size = false;
960 for (unsigned i = 0; i < phase->effects.size(); ++i) {
961 Effect *effect = phase->effects[i]->effect;
962 if (effect->num_inputs() != 0) {
966 Input *input = static_cast<Input *>(effect);
967 if (output_width == 0 && output_height == 0) {
968 output_width = input->get_width();
969 output_height = input->get_height();
970 } else if (output_width != input->get_width() ||
971 output_height != input->get_height()) {
972 all_inputs_same_size = false;
976 if (all_inputs_same_size) {
977 assert(output_width != 0);
978 assert(output_height != 0);
979 phase->virtual_output_width = phase->output_width = output_width;
980 phase->virtual_output_height = phase->output_height = output_height;
984 // If not, fit all the inputs into the current aspect, and select the largest one.
987 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
988 Phase *input = phase->inputs[i];
989 assert(input->output_width != 0);
990 assert(input->output_height != 0);
991 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
993 for (unsigned i = 0; i < phase->effects.size(); ++i) {
994 Effect *effect = phase->effects[i]->effect;
995 if (effect->num_inputs() != 0) {
999 Input *input = static_cast<Input *>(effect);
1000 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
1002 assert(output_width != 0);
1003 assert(output_height != 0);
1004 phase->virtual_output_width = phase->output_width = output_width;
1005 phase->virtual_output_height = phase->output_height = output_height;
1008 void EffectChain::sort_all_nodes_topologically()
1010 nodes = topological_sort(nodes);
1013 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
1015 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
1016 vector<Node *> sorted_list;
1017 for (unsigned i = 0; i < nodes.size(); ++i) {
1018 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
1020 reverse(sorted_list.begin(), sorted_list.end());
1024 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
1026 if (nodes_left_to_visit->count(node) == 0) {
1029 nodes_left_to_visit->erase(node);
1030 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
1031 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
1033 sorted_list->push_back(node);
1036 void EffectChain::find_color_spaces_for_inputs()
1038 for (unsigned i = 0; i < nodes.size(); ++i) {
1039 Node *node = nodes[i];
1040 if (node->disabled) {
1043 if (node->incoming_links.size() == 0) {
1044 Input *input = static_cast<Input *>(node->effect);
1045 node->output_color_space = input->get_color_space();
1046 node->output_gamma_curve = input->get_gamma_curve();
1048 Effect::AlphaHandling alpha_handling = input->alpha_handling();
1049 switch (alpha_handling) {
1050 case Effect::OUTPUT_BLANK_ALPHA:
1051 node->output_alpha_type = ALPHA_BLANK;
1053 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
1054 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1056 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
1057 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1059 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
1060 case Effect::DONT_CARE_ALPHA_TYPE:
1065 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
1066 assert(node->output_gamma_curve == GAMMA_LINEAR);
1072 // Propagate gamma and color space information as far as we can in the graph.
1073 // The rules are simple: Anything where all the inputs agree, get that as
1074 // output as well. Anything else keeps having *_INVALID.
1075 void EffectChain::propagate_gamma_and_color_space()
1077 // We depend on going through the nodes in order.
1078 sort_all_nodes_topologically();
1080 for (unsigned i = 0; i < nodes.size(); ++i) {
1081 Node *node = nodes[i];
1082 if (node->disabled) {
1085 assert(node->incoming_links.size() == node->effect->num_inputs());
1086 if (node->incoming_links.size() == 0) {
1087 assert(node->output_color_space != COLORSPACE_INVALID);
1088 assert(node->output_gamma_curve != GAMMA_INVALID);
1092 Colorspace color_space = node->incoming_links[0]->output_color_space;
1093 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1094 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1095 if (node->incoming_links[j]->output_color_space != color_space) {
1096 color_space = COLORSPACE_INVALID;
1098 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1099 gamma_curve = GAMMA_INVALID;
1103 // The conversion effects already have their outputs set correctly,
1104 // so leave them alone.
1105 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1106 node->output_color_space = color_space;
1108 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1109 node->effect->effect_type_id() != "GammaExpansionEffect") {
1110 node->output_gamma_curve = gamma_curve;
1115 // Propagate alpha information as far as we can in the graph.
1116 // Similar to propagate_gamma_and_color_space().
1117 void EffectChain::propagate_alpha()
1119 // We depend on going through the nodes in order.
1120 sort_all_nodes_topologically();
1122 for (unsigned i = 0; i < nodes.size(); ++i) {
1123 Node *node = nodes[i];
1124 if (node->disabled) {
1127 assert(node->incoming_links.size() == node->effect->num_inputs());
1128 if (node->incoming_links.size() == 0) {
1129 assert(node->output_alpha_type != ALPHA_INVALID);
1133 // The alpha multiplication/division effects are special cases.
1134 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1135 assert(node->incoming_links.size() == 1);
1136 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1137 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1140 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1141 assert(node->incoming_links.size() == 1);
1142 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1143 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1147 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1148 // because they are the only one that _need_ postmultiplied alpha.
1149 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1150 node->effect->effect_type_id() == "GammaExpansionEffect") {
1151 assert(node->incoming_links.size() == 1);
1152 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1153 node->output_alpha_type = ALPHA_BLANK;
1154 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1155 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1157 node->output_alpha_type = ALPHA_INVALID;
1162 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1163 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1164 // taken care of above. Rationale: Even if you could imagine
1165 // e.g. an effect that took in an image and set alpha=1.0
1166 // unconditionally, it wouldn't make any sense to have it as
1167 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1168 // got its input pre- or postmultiplied, so it wouldn't know
1169 // whether to divide away the old alpha or not.
1170 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1171 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1172 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1173 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1175 // If the node has multiple inputs, check that they are all valid and
1177 bool any_invalid = false;
1178 bool any_premultiplied = false;
1179 bool any_postmultiplied = false;
1181 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1182 switch (node->incoming_links[j]->output_alpha_type) {
1187 // Blank is good as both pre- and postmultiplied alpha,
1188 // so just ignore it.
1190 case ALPHA_PREMULTIPLIED:
1191 any_premultiplied = true;
1193 case ALPHA_POSTMULTIPLIED:
1194 any_postmultiplied = true;
1202 node->output_alpha_type = ALPHA_INVALID;
1206 // Inputs must be of the same type.
1207 if (any_premultiplied && any_postmultiplied) {
1208 node->output_alpha_type = ALPHA_INVALID;
1212 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1213 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1214 // This combination (requiring premultiplied alpha, but _not_ requiring
1215 // linear light) is illegal, since the combination of premultiplied alpha
1216 // and nonlinear inputs is meaningless.
1217 assert(node->effect->needs_linear_light());
1219 // If the effect has asked for premultiplied alpha, check that it has got it.
1220 if (any_postmultiplied) {
1221 node->output_alpha_type = ALPHA_INVALID;
1222 } else if (!any_premultiplied &&
1223 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1224 // Blank input alpha, and the effect preserves blank alpha.
1225 node->output_alpha_type = ALPHA_BLANK;
1227 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1230 // OK, all inputs are the same, and this effect is not going
1232 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1233 if (any_premultiplied) {
1234 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1235 } else if (any_postmultiplied) {
1236 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1238 node->output_alpha_type = ALPHA_BLANK;
1244 bool EffectChain::node_needs_colorspace_fix(Node *node)
1246 if (node->disabled) {
1249 if (node->effect->num_inputs() == 0) {
1253 // propagate_gamma_and_color_space() has already set our output
1254 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1255 if (node->output_color_space == COLORSPACE_INVALID) {
1258 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1261 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1262 // the graph. Our strategy is not always optimal, but quite simple:
1263 // Find an effect that's as early as possible where the inputs are of
1264 // unacceptable colorspaces (that is, either different, or, if the effect only
1265 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1266 // propagate the information anew, and repeat until there are no more such
1268 void EffectChain::fix_internal_color_spaces()
1270 unsigned colorspace_propagation_pass = 0;
1274 for (unsigned i = 0; i < nodes.size(); ++i) {
1275 Node *node = nodes[i];
1276 if (!node_needs_colorspace_fix(node)) {
1280 // Go through each input that is not sRGB, and insert
1281 // a colorspace conversion after it.
1282 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1283 Node *input = node->incoming_links[j];
1284 assert(input->output_color_space != COLORSPACE_INVALID);
1285 if (input->output_color_space == COLORSPACE_sRGB) {
1288 Node *conversion = add_node(new ColorspaceConversionEffect());
1289 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1290 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1291 conversion->output_color_space = COLORSPACE_sRGB;
1292 replace_sender(input, conversion);
1293 connect_nodes(input, conversion);
1296 // Re-sort topologically, and propagate the new information.
1297 propagate_gamma_and_color_space();
1304 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1305 output_dot(filename);
1306 assert(colorspace_propagation_pass < 100);
1307 } while (found_any);
1309 for (unsigned i = 0; i < nodes.size(); ++i) {
1310 Node *node = nodes[i];
1311 if (node->disabled) {
1314 assert(node->output_color_space != COLORSPACE_INVALID);
1318 bool EffectChain::node_needs_alpha_fix(Node *node)
1320 if (node->disabled) {
1324 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1325 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1326 return (node->output_alpha_type == ALPHA_INVALID);
1329 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1330 // the graph. Similar to fix_internal_color_spaces().
1331 void EffectChain::fix_internal_alpha(unsigned step)
1333 unsigned alpha_propagation_pass = 0;
1337 for (unsigned i = 0; i < nodes.size(); ++i) {
1338 Node *node = nodes[i];
1339 if (!node_needs_alpha_fix(node)) {
1343 // If we need to fix up GammaExpansionEffect, then clearly something
1344 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1346 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1348 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1350 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1351 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1352 assert(node->incoming_links.size() == 1);
1353 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1354 desired_type = ALPHA_POSTMULTIPLIED;
1357 // Go through each input that is not premultiplied alpha, and insert
1358 // a conversion before it.
1359 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1360 Node *input = node->incoming_links[j];
1361 assert(input->output_alpha_type != ALPHA_INVALID);
1362 if (input->output_alpha_type == desired_type ||
1363 input->output_alpha_type == ALPHA_BLANK) {
1367 if (desired_type == ALPHA_PREMULTIPLIED) {
1368 conversion = add_node(new AlphaMultiplicationEffect());
1370 conversion = add_node(new AlphaDivisionEffect());
1372 conversion->output_alpha_type = desired_type;
1373 replace_sender(input, conversion);
1374 connect_nodes(input, conversion);
1377 // Re-sort topologically, and propagate the new information.
1378 propagate_gamma_and_color_space();
1386 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1387 output_dot(filename);
1388 assert(alpha_propagation_pass < 100);
1389 } while (found_any);
1391 for (unsigned i = 0; i < nodes.size(); ++i) {
1392 Node *node = nodes[i];
1393 if (node->disabled) {
1396 assert(node->output_alpha_type != ALPHA_INVALID);
1400 // Make so that the output is in the desired color space.
1401 void EffectChain::fix_output_color_space()
1403 Node *output = find_output_node();
1404 if (output->output_color_space != output_format.color_space) {
1405 Node *conversion = add_node(new ColorspaceConversionEffect());
1406 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1407 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1408 conversion->output_color_space = output_format.color_space;
1409 connect_nodes(output, conversion);
1411 propagate_gamma_and_color_space();
1415 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1416 void EffectChain::fix_output_alpha()
1418 Node *output = find_output_node();
1419 assert(output->output_alpha_type != ALPHA_INVALID);
1420 if (output->output_alpha_type == ALPHA_BLANK) {
1421 // No alpha output, so we don't care.
1424 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1425 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1426 Node *conversion = add_node(new AlphaDivisionEffect());
1427 connect_nodes(output, conversion);
1429 propagate_gamma_and_color_space();
1431 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1432 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1433 Node *conversion = add_node(new AlphaMultiplicationEffect());
1434 connect_nodes(output, conversion);
1436 propagate_gamma_and_color_space();
1440 bool EffectChain::node_needs_gamma_fix(Node *node)
1442 if (node->disabled) {
1446 // Small hack since the output is not an explicit node:
1447 // If we are the last node and our output is in the wrong
1448 // space compared to EffectChain's output, we need to fix it.
1449 // This will only take us to linear, but fix_output_gamma()
1450 // will come and take us to the desired output gamma
1453 // This needs to be before everything else, since it could
1454 // even apply to inputs (if they are the only effect).
1455 if (node->outgoing_links.empty() &&
1456 node->output_gamma_curve != output_format.gamma_curve &&
1457 node->output_gamma_curve != GAMMA_LINEAR) {
1461 if (node->effect->num_inputs() == 0) {
1465 // propagate_gamma_and_color_space() has already set our output
1466 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1467 // except for GammaCompressionEffect.
1468 if (node->output_gamma_curve == GAMMA_INVALID) {
1471 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1472 assert(node->incoming_links.size() == 1);
1473 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1476 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1479 // Very similar to fix_internal_color_spaces(), but for gamma.
1480 // There is one difference, though; before we start adding conversion nodes,
1481 // we see if we can get anything out of asking the sources to deliver
1482 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1483 // does that part, while fix_internal_gamma_by_inserting_nodes()
1484 // inserts nodes as needed afterwards.
1485 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1487 unsigned gamma_propagation_pass = 0;
1491 for (unsigned i = 0; i < nodes.size(); ++i) {
1492 Node *node = nodes[i];
1493 if (!node_needs_gamma_fix(node)) {
1497 // See if all inputs can give us linear gamma. If not, leave it.
1498 vector<Node *> nonlinear_inputs;
1499 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1500 assert(!nonlinear_inputs.empty());
1503 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1504 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1505 all_ok &= input->can_output_linear_gamma();
1512 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1513 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1514 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1517 // Re-sort topologically, and propagate the new information.
1518 propagate_gamma_and_color_space();
1525 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1526 output_dot(filename);
1527 assert(gamma_propagation_pass < 100);
1528 } while (found_any);
1531 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1533 unsigned gamma_propagation_pass = 0;
1537 for (unsigned i = 0; i < nodes.size(); ++i) {
1538 Node *node = nodes[i];
1539 if (!node_needs_gamma_fix(node)) {
1543 // Special case: We could be an input and still be asked to
1544 // fix our gamma; if so, we should be the only node
1545 // (as node_needs_gamma_fix() would only return true in
1546 // for an input in that case). That means we should insert
1547 // a conversion node _after_ ourselves.
1548 if (node->incoming_links.empty()) {
1549 assert(node->outgoing_links.empty());
1550 Node *conversion = add_node(new GammaExpansionEffect());
1551 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1552 conversion->output_gamma_curve = GAMMA_LINEAR;
1553 connect_nodes(node, conversion);
1556 // If not, go through each input that is not linear gamma,
1557 // and insert a gamma conversion after it.
1558 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1559 Node *input = node->incoming_links[j];
1560 assert(input->output_gamma_curve != GAMMA_INVALID);
1561 if (input->output_gamma_curve == GAMMA_LINEAR) {
1564 Node *conversion = add_node(new GammaExpansionEffect());
1565 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1566 conversion->output_gamma_curve = GAMMA_LINEAR;
1567 replace_sender(input, conversion);
1568 connect_nodes(input, conversion);
1571 // Re-sort topologically, and propagate the new information.
1573 propagate_gamma_and_color_space();
1580 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1581 output_dot(filename);
1582 assert(gamma_propagation_pass < 100);
1583 } while (found_any);
1585 for (unsigned i = 0; i < nodes.size(); ++i) {
1586 Node *node = nodes[i];
1587 if (node->disabled) {
1590 assert(node->output_gamma_curve != GAMMA_INVALID);
1594 // Make so that the output is in the desired gamma.
1595 // Note that this assumes linear input gamma, so it might create the need
1596 // for another pass of fix_internal_gamma().
1597 void EffectChain::fix_output_gamma()
1599 Node *output = find_output_node();
1600 if (output->output_gamma_curve != output_format.gamma_curve) {
1601 Node *conversion = add_node(new GammaCompressionEffect());
1602 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1603 conversion->output_gamma_curve = output_format.gamma_curve;
1604 connect_nodes(output, conversion);
1608 // If the user has requested Y'CbCr output, we need to do this conversion
1609 // _after_ GammaCompressionEffect etc., but before dither (see below).
1610 // This is because Y'CbCr, with the exception of a special optional mode
1611 // in Rec. 2020 (which we currently don't support), is defined to work on
1612 // gamma-encoded data.
1613 void EffectChain::add_ycbcr_conversion_if_needed()
1615 assert(output_color_rgba || output_color_ycbcr);
1616 if (!output_color_ycbcr) {
1619 Node *output = find_output_node();
1620 ycbcr_conversion_effect_node = add_node(new YCbCrConversionEffect(output_ycbcr_format));
1621 connect_nodes(output, ycbcr_conversion_effect_node);
1624 // If the user has requested dither, add a DitherEffect right at the end
1625 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1626 // since dither is about the only effect that can _not_ be done in linear space.
1627 void EffectChain::add_dither_if_needed()
1629 if (num_dither_bits == 0) {
1632 Node *output = find_output_node();
1633 Node *dither = add_node(new DitherEffect());
1634 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1635 connect_nodes(output, dither);
1637 dither_effect = dither->effect;
1640 // Find the output node. This is, simply, one that has no outgoing links.
1641 // If there are multiple ones, the graph is malformed (we do not support
1642 // multiple outputs right now).
1643 Node *EffectChain::find_output_node()
1645 vector<Node *> output_nodes;
1646 for (unsigned i = 0; i < nodes.size(); ++i) {
1647 Node *node = nodes[i];
1648 if (node->disabled) {
1651 if (node->outgoing_links.empty()) {
1652 output_nodes.push_back(node);
1655 assert(output_nodes.size() == 1);
1656 return output_nodes[0];
1659 void EffectChain::finalize()
1661 // Output the graph as it is before we do any conversions on it.
1662 output_dot("step0-start.dot");
1664 // Give each effect in turn a chance to rewrite its own part of the graph.
1665 // Note that if more effects are added as part of this, they will be
1666 // picked up as part of the same for loop, since they are added at the end.
1667 for (unsigned i = 0; i < nodes.size(); ++i) {
1668 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1670 output_dot("step1-rewritten.dot");
1672 find_color_spaces_for_inputs();
1673 output_dot("step2-input-colorspace.dot");
1676 output_dot("step3-propagated-alpha.dot");
1678 propagate_gamma_and_color_space();
1679 output_dot("step4-propagated-all.dot");
1681 fix_internal_color_spaces();
1682 fix_internal_alpha(6);
1683 fix_output_color_space();
1684 output_dot("step7-output-colorspacefix.dot");
1686 output_dot("step8-output-alphafix.dot");
1688 // Note that we need to fix gamma after colorspace conversion,
1689 // because colorspace conversions might create needs for gamma conversions.
1690 // Also, we need to run an extra pass of fix_internal_gamma() after
1691 // fixing the output gamma, as we only have conversions to/from linear,
1692 // and fix_internal_alpha() since GammaCompressionEffect needs
1693 // postmultiplied input.
1694 fix_internal_gamma_by_asking_inputs(9);
1695 fix_internal_gamma_by_inserting_nodes(10);
1697 output_dot("step11-output-gammafix.dot");
1699 output_dot("step12-output-alpha-propagated.dot");
1700 fix_internal_alpha(13);
1701 output_dot("step14-output-alpha-fixed.dot");
1702 fix_internal_gamma_by_asking_inputs(15);
1703 fix_internal_gamma_by_inserting_nodes(16);
1705 output_dot("step17-before-ycbcr.dot");
1706 add_ycbcr_conversion_if_needed();
1708 output_dot("step18-before-dither.dot");
1709 add_dither_if_needed();
1711 output_dot("step19-final.dot");
1713 // Construct all needed GLSL programs, starting at the output.
1714 // We need to keep track of which effects have already been computed,
1715 // as an effect with multiple users could otherwise be calculated
1717 map<Node *, Phase *> completed_effects;
1718 construct_phase(find_output_node(), &completed_effects);
1720 output_dot("step20-split-to-phases.dot");
1722 assert(phases[0]->inputs.empty());
1727 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1731 // This needs to be set anew, in case we are coming from a different context
1732 // from when we initialized.
1734 glDisable(GL_DITHER);
1737 const bool final_srgb = glIsEnabled(GL_FRAMEBUFFER_SRGB);
1739 bool current_srgb = final_srgb;
1741 // Save original viewport.
1742 GLuint x = 0, y = 0;
1744 if (width == 0 && height == 0) {
1746 glGetIntegerv(GL_VIEWPORT, viewport);
1749 width = viewport[2];
1750 height = viewport[3];
1755 glDisable(GL_BLEND);
1757 glDisable(GL_DEPTH_TEST);
1759 glDepthMask(GL_FALSE);
1762 // Generate a VAO that will be used during the entire execution,
1763 // and bind the VBO, since it contains all the data.
1765 glGenVertexArrays(1, &vao);
1767 glBindVertexArray(vao);
1769 glBindBuffer(GL_ARRAY_BUFFER, vbo);
1771 set<GLint> bound_attribute_indices;
1773 set<Phase *> generated_mipmaps;
1775 // We choose the simplest option of having one texture per output,
1776 // since otherwise this turns into an (albeit simple) register allocation problem.
1777 map<Phase *, GLuint> output_textures;
1779 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1780 Phase *phase = phases[phase_num];
1782 if (do_phase_timing) {
1783 GLuint timer_query_object;
1784 if (phase->timer_query_objects_free.empty()) {
1785 glGenQueries(1, &timer_query_object);
1787 timer_query_object = phase->timer_query_objects_free.front();
1788 phase->timer_query_objects_free.pop_front();
1790 glBeginQuery(GL_TIME_ELAPSED, timer_query_object);
1791 phase->timer_query_objects_running.push_back(timer_query_object);
1793 if (phase_num == phases.size() - 1) {
1794 // Last phase goes to the output the user specified.
1795 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1797 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1798 assert(status == GL_FRAMEBUFFER_COMPLETE);
1799 glViewport(x, y, width, height);
1800 if (dither_effect != NULL) {
1801 CHECK(dither_effect->set_int("output_width", width));
1802 CHECK(dither_effect->set_int("output_height", height));
1805 bool last_phase = (phase_num == phases.size() - 1);
1807 // Enable sRGB rendering for intermediates in case we are
1808 // rendering to an sRGB format.
1809 bool needs_srgb = last_phase ? final_srgb : true;
1810 if (needs_srgb && !current_srgb) {
1811 glEnable(GL_FRAMEBUFFER_SRGB);
1813 current_srgb = true;
1814 } else if (!needs_srgb && current_srgb) {
1815 glDisable(GL_FRAMEBUFFER_SRGB);
1817 current_srgb = true;
1820 execute_phase(phase, last_phase, &bound_attribute_indices, &output_textures, &generated_mipmaps);
1821 if (do_phase_timing) {
1822 glEndQuery(GL_TIME_ELAPSED);
1826 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1827 texture_it != output_textures.end();
1829 resource_pool->release_2d_texture(texture_it->second);
1832 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1837 glBindBuffer(GL_ARRAY_BUFFER, 0);
1839 glBindVertexArray(0);
1841 glDeleteVertexArrays(1, &vao);
1844 if (do_phase_timing) {
1845 // Get back the timer queries.
1846 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1847 Phase *phase = phases[phase_num];
1848 for (std::list<GLuint>::iterator timer_it = phase->timer_query_objects_running.begin();
1849 timer_it != phase->timer_query_objects_running.end(); ) {
1850 GLint timer_query_object = *timer_it;
1852 glGetQueryObjectiv(timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1854 GLuint64 time_elapsed;
1855 glGetQueryObjectui64v(timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1856 phase->time_elapsed_ns += time_elapsed;
1857 ++phase->num_measured_iterations;
1858 phase->timer_query_objects_free.push_back(timer_query_object);
1859 phase->timer_query_objects_running.erase(timer_it++);
1868 void EffectChain::enable_phase_timing(bool enable)
1871 assert(movit_timer_queries_supported);
1873 this->do_phase_timing = enable;
1876 void EffectChain::reset_phase_timing()
1878 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1879 Phase *phase = phases[phase_num];
1880 phase->time_elapsed_ns = 0;
1881 phase->num_measured_iterations = 0;
1885 void EffectChain::print_phase_timing()
1887 double total_time_ms = 0.0;
1888 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1889 Phase *phase = phases[phase_num];
1890 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1891 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1892 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1893 if (effect_num != 0) {
1896 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1899 total_time_ms += avg_time_ms;
1901 printf("Total: %5.1f ms\n", total_time_ms);
1904 void EffectChain::execute_phase(Phase *phase, bool last_phase,
1905 set<GLint> *bound_attribute_indices,
1906 map<Phase *, GLuint> *output_textures,
1907 set<Phase *> *generated_mipmaps)
1911 // Find a texture for this phase.
1912 inform_input_sizes(phase);
1914 find_output_size(phase);
1916 GLuint tex_num = resource_pool->create_2d_texture(intermediate_format, phase->output_width, phase->output_height);
1917 output_textures->insert(make_pair(phase, tex_num));
1920 // Set up RTT inputs for this phase.
1921 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1922 glActiveTexture(GL_TEXTURE0 + sampler);
1923 Phase *input = phase->inputs[sampler];
1924 input->output_node->bound_sampler_num = sampler;
1925 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1927 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1928 glGenerateMipmap(GL_TEXTURE_2D);
1930 generated_mipmaps->insert(input);
1932 setup_rtt_sampler(sampler, phase->input_needs_mipmaps);
1933 phase->input_samplers[sampler] = sampler; // Bind the sampler to the right uniform.
1936 // And now the output. (Already set up for us if it is the last phase.)
1938 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1939 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1940 glViewport(0, 0, phase->output_width, phase->output_height);
1943 GLuint instance_program_num = resource_pool->use_glsl_program(phase->glsl_program_num);
1946 // Give the required parameters to all the effects.
1947 unsigned sampler_num = phase->inputs.size();
1948 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1949 Node *node = phase->effects[i];
1950 unsigned old_sampler_num = sampler_num;
1951 node->effect->set_gl_state(instance_program_num, phase->effect_ids[node], &sampler_num);
1954 if (node->effect->is_single_texture()) {
1955 assert(sampler_num - old_sampler_num == 1);
1956 node->bound_sampler_num = old_sampler_num;
1958 node->bound_sampler_num = -1;
1962 // Uniforms need to come after set_gl_state(), since they can be updated
1964 setup_uniforms(phase);
1966 // Clean up old attributes if they are no longer needed.
1967 for (set<GLint>::iterator attr_it = bound_attribute_indices->begin();
1968 attr_it != bound_attribute_indices->end(); ) {
1969 if (phase->attribute_indexes.count(*attr_it) == 0) {
1970 glDisableVertexAttribArray(*attr_it);
1972 bound_attribute_indices->erase(attr_it++);
1978 // Set up the new attributes, if needed.
1979 for (set<GLint>::iterator attr_it = phase->attribute_indexes.begin();
1980 attr_it != phase->attribute_indexes.end();
1982 if (bound_attribute_indices->count(*attr_it) == 0) {
1983 glEnableVertexAttribArray(*attr_it);
1985 glVertexAttribPointer(*attr_it, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1987 bound_attribute_indices->insert(*attr_it);
1991 glDrawArrays(GL_TRIANGLES, 0, 3);
1994 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1995 Node *node = phase->effects[i];
1996 node->effect->clear_gl_state();
1999 resource_pool->unuse_glsl_program(instance_program_num);
2002 resource_pool->release_fbo(fbo);
2006 void EffectChain::setup_uniforms(Phase *phase)
2008 // TODO: Use UBO blocks.
2009 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
2010 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
2011 if (uniform.location != -1) {
2012 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2015 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
2016 const Uniform<bool> &uniform = phase->uniforms_bool[i];
2017 assert(uniform.num_values == 1);
2018 if (uniform.location != -1) {
2019 glUniform1i(uniform.location, *uniform.value);
2022 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
2023 const Uniform<int> &uniform = phase->uniforms_int[i];
2024 if (uniform.location != -1) {
2025 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2028 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
2029 const Uniform<float> &uniform = phase->uniforms_float[i];
2030 if (uniform.location != -1) {
2031 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
2034 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
2035 const Uniform<float> &uniform = phase->uniforms_vec2[i];
2036 if (uniform.location != -1) {
2037 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
2040 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
2041 const Uniform<float> &uniform = phase->uniforms_vec3[i];
2042 if (uniform.location != -1) {
2043 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
2046 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
2047 const Uniform<float> &uniform = phase->uniforms_vec4[i];
2048 if (uniform.location != -1) {
2049 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
2052 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
2053 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
2054 assert(uniform.num_values == 1);
2055 if (uniform.location != -1) {
2056 // Convert to float (GLSL has no double matrices).
2058 for (unsigned y = 0; y < 3; ++y) {
2059 for (unsigned x = 0; x < 3; ++x) {
2060 matrixf[y + x * 3] = (*uniform.value)(y, x);
2063 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
2068 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
2070 glActiveTexture(GL_TEXTURE0 + sampler_num);
2073 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
2076 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2079 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2081 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2085 } // namespace movit