1 #define GL_GLEXT_PROTOTYPES 1
17 #include "alpha_division_effect.h"
18 #include "alpha_multiplication_effect.h"
19 #include "colorspace_conversion_effect.h"
20 #include "dither_effect.h"
22 #include "effect_chain.h"
23 #include "effect_util.h"
24 #include "gamma_compression_effect.h"
25 #include "gamma_expansion_effect.h"
28 #include "resource_pool.h"
30 #include "ycbcr_conversion_effect.h"
32 using namespace Eigen;
37 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
38 : aspect_nom(aspect_nom),
39 aspect_denom(aspect_denom),
43 resource_pool(resource_pool),
44 do_phase_timing(false) {
45 if (resource_pool == NULL) {
46 this->resource_pool = new ResourcePool();
47 owns_resource_pool = true;
49 owns_resource_pool = false;
53 EffectChain::~EffectChain()
55 for (unsigned i = 0; i < nodes.size(); ++i) {
56 delete nodes[i]->effect;
59 for (unsigned i = 0; i < phases.size(); ++i) {
60 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
63 if (owns_resource_pool) {
68 Input *EffectChain::add_input(Input *input)
71 inputs.push_back(input);
76 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
79 output_format = format;
80 output_alpha_format = alpha_format;
81 output_color_type = OUTPUT_COLOR_RGB;
84 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
85 const YCbCrFormat &ycbcr_format)
88 output_format = format;
89 output_alpha_format = alpha_format;
90 output_color_type = OUTPUT_COLOR_YCBCR;
91 output_ycbcr_format = ycbcr_format;
93 assert(ycbcr_format.chroma_subsampling_x == 1);
94 assert(ycbcr_format.chroma_subsampling_y == 1);
97 Node *EffectChain::add_node(Effect *effect)
99 for (unsigned i = 0; i < nodes.size(); ++i) {
100 assert(nodes[i]->effect != effect);
103 Node *node = new Node;
104 node->effect = effect;
105 node->disabled = false;
106 node->output_color_space = COLORSPACE_INVALID;
107 node->output_gamma_curve = GAMMA_INVALID;
108 node->output_alpha_type = ALPHA_INVALID;
109 node->needs_mipmaps = false;
110 node->one_to_one_sampling = false;
112 nodes.push_back(node);
113 node_map[effect] = node;
114 effect->inform_added(this);
118 void EffectChain::connect_nodes(Node *sender, Node *receiver)
120 sender->outgoing_links.push_back(receiver);
121 receiver->incoming_links.push_back(sender);
124 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
126 new_receiver->incoming_links = old_receiver->incoming_links;
127 old_receiver->incoming_links.clear();
129 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
130 Node *sender = new_receiver->incoming_links[i];
131 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
132 if (sender->outgoing_links[j] == old_receiver) {
133 sender->outgoing_links[j] = new_receiver;
139 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
141 new_sender->outgoing_links = old_sender->outgoing_links;
142 old_sender->outgoing_links.clear();
144 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
145 Node *receiver = new_sender->outgoing_links[i];
146 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
147 if (receiver->incoming_links[j] == old_sender) {
148 receiver->incoming_links[j] = new_sender;
154 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
156 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
157 if (sender->outgoing_links[i] == receiver) {
158 sender->outgoing_links[i] = middle;
159 middle->incoming_links.push_back(sender);
162 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
163 if (receiver->incoming_links[i] == sender) {
164 receiver->incoming_links[i] = middle;
165 middle->outgoing_links.push_back(receiver);
169 assert(middle->incoming_links.size() == middle->effect->num_inputs());
172 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
174 assert(node->effect->needs_texture_bounce());
175 assert(input_num < node->incoming_links.size());
176 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
177 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
178 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
181 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
183 if (node->output_gamma_curve == GAMMA_LINEAR &&
184 node->effect->effect_type_id() != "GammaCompressionEffect") {
187 if (node->effect->num_inputs() == 0) {
188 nonlinear_inputs->push_back(node);
190 assert(node->effect->num_inputs() == node->incoming_links.size());
191 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
192 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
197 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
200 assert(inputs.size() == effect->num_inputs());
201 Node *node = add_node(effect);
202 for (unsigned i = 0; i < inputs.size(); ++i) {
203 assert(node_map.count(inputs[i]) != 0);
204 connect_nodes(node_map[inputs[i]], node);
209 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
210 string replace_prefix(const string &text, const string &prefix)
215 while (start < text.size()) {
216 size_t pos = text.find("PREFIX(", start);
217 if (pos == string::npos) {
218 output.append(text.substr(start, string::npos));
222 output.append(text.substr(start, pos - start));
223 output.append(prefix);
226 pos += strlen("PREFIX(");
228 // Output stuff until we find the matching ), which we then eat.
230 size_t end_arg_pos = pos;
231 while (end_arg_pos < text.size()) {
232 if (text[end_arg_pos] == '(') {
234 } else if (text[end_arg_pos] == ')') {
242 output.append(text.substr(pos, end_arg_pos - pos));
250 void EffectChain::compile_glsl_program(Phase *phase)
252 string frag_shader_header = read_version_dependent_file("header", "frag");
253 string frag_shader = "";
255 // Create functions and uniforms for all the texture inputs that we need.
256 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
257 Node *input = phase->inputs[i]->output_node;
259 sprintf(effect_id, "in%u", i);
260 phase->effect_ids.insert(make_pair(input, effect_id));
262 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
263 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
264 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
265 frag_shader += "}\n";
268 Uniform<int> uniform;
269 uniform.name = effect_id;
270 uniform.value = &phase->input_samplers[i];
271 uniform.prefix = "tex";
272 uniform.num_values = 1;
273 uniform.location = -1;
274 phase->uniforms_sampler2d.push_back(uniform);
277 // Give each effect in the phase its own ID.
278 for (unsigned i = 0; i < phase->effects.size(); ++i) {
279 Node *node = phase->effects[i];
281 sprintf(effect_id, "eff%u", i);
282 phase->effect_ids.insert(make_pair(node, effect_id));
285 for (unsigned i = 0; i < phase->effects.size(); ++i) {
286 Node *node = phase->effects[i];
287 const string effect_id = phase->effect_ids[node];
288 if (node->incoming_links.size() == 1) {
289 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
291 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
293 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
299 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
300 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
301 frag_shader += "#undef PREFIX\n";
302 frag_shader += "#undef FUNCNAME\n";
303 if (node->incoming_links.size() == 1) {
304 frag_shader += "#undef INPUT\n";
306 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
308 sprintf(buf, "#undef INPUT%d\n", j + 1);
314 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
315 frag_shader.append(read_version_dependent_file("footer", "frag"));
317 // Collect uniforms from all effects and output them. Note that this needs
318 // to happen after output_fragment_shader(), even though the uniforms come
319 // before in the output source, since output_fragment_shader() is allowed
320 // to register new uniforms (e.g. arrays that are of unknown length until
321 // finalization time).
322 // TODO: Make a uniform block for platforms that support it.
323 string frag_shader_uniforms = "";
324 for (unsigned i = 0; i < phase->effects.size(); ++i) {
325 Node *node = phase->effects[i];
326 Effect *effect = node->effect;
327 const string effect_id = phase->effect_ids[node];
328 for (unsigned j = 0; j < effect->uniforms_sampler2d.size(); ++j) {
329 phase->uniforms_sampler2d.push_back(effect->uniforms_sampler2d[j]);
330 phase->uniforms_sampler2d.back().prefix = effect_id;
331 frag_shader_uniforms += string("uniform sampler2D ") + effect_id
332 + "_" + effect->uniforms_sampler2d[j].name + ";\n";
334 for (unsigned j = 0; j < effect->uniforms_bool.size(); ++j) {
335 phase->uniforms_bool.push_back(effect->uniforms_bool[j]);
336 phase->uniforms_bool.back().prefix = effect_id;
337 frag_shader_uniforms += string("uniform bool ") + effect_id
338 + "_" + effect->uniforms_bool[j].name + ";\n";
340 for (unsigned j = 0; j < effect->uniforms_int.size(); ++j) {
341 phase->uniforms_int.push_back(effect->uniforms_int[j]);
342 phase->uniforms_int.back().prefix = effect_id;
343 frag_shader_uniforms += string("uniform int ") + effect_id
344 + "_" + effect->uniforms_int[j].name + ";\n";
346 for (unsigned j = 0; j < effect->uniforms_float.size(); ++j) {
347 phase->uniforms_float.push_back(effect->uniforms_float[j]);
348 phase->uniforms_float.back().prefix = effect_id;
349 frag_shader_uniforms += string("uniform float ") + effect_id
350 + "_" + effect->uniforms_float[j].name + ";\n";
352 for (unsigned j = 0; j < effect->uniforms_vec2.size(); ++j) {
353 phase->uniforms_vec2.push_back(effect->uniforms_vec2[j]);
354 phase->uniforms_vec2.back().prefix = effect_id;
355 frag_shader_uniforms += string("uniform vec2 ") + effect_id
356 + "_" + effect->uniforms_vec2[j].name + ";\n";
358 for (unsigned j = 0; j < effect->uniforms_vec3.size(); ++j) {
359 phase->uniforms_vec3.push_back(effect->uniforms_vec3[j]);
360 phase->uniforms_vec3.back().prefix = effect_id;
361 frag_shader_uniforms += string("uniform vec3 ") + effect_id
362 + "_" + effect->uniforms_vec3[j].name + ";\n";
364 for (unsigned j = 0; j < effect->uniforms_vec4.size(); ++j) {
365 phase->uniforms_vec4.push_back(effect->uniforms_vec4[j]);
366 phase->uniforms_vec4.back().prefix = effect_id;
367 frag_shader_uniforms += string("uniform vec4 ") + effect_id
368 + "_" + effect->uniforms_vec4[j].name + ";\n";
370 for (unsigned j = 0; j < effect->uniforms_vec2_array.size(); ++j) {
372 phase->uniforms_vec2.push_back(effect->uniforms_vec2_array[j]);
373 phase->uniforms_vec2.back().prefix = effect_id;
374 snprintf(buf, sizeof(buf), "uniform vec2 %s_%s[%d];\n",
375 effect_id.c_str(), effect->uniforms_vec2_array[j].name.c_str(),
376 int(effect->uniforms_vec2_array[j].num_values));
377 frag_shader_uniforms += buf;
379 for (unsigned j = 0; j < effect->uniforms_vec4_array.size(); ++j) {
381 phase->uniforms_vec4.push_back(effect->uniforms_vec4_array[j]);
382 phase->uniforms_vec4.back().prefix = effect_id;
383 snprintf(buf, sizeof(buf), "uniform vec4 %s_%s[%d];\n",
384 effect_id.c_str(), effect->uniforms_vec4_array[j].name.c_str(),
385 int(effect->uniforms_vec4_array[j].num_values));
386 frag_shader_uniforms += buf;
388 for (unsigned j = 0; j < effect->uniforms_mat3.size(); ++j) {
389 phase->uniforms_mat3.push_back(effect->uniforms_mat3[j]);
390 phase->uniforms_mat3.back().prefix = effect_id;
391 frag_shader_uniforms += string("uniform mat3 ") + effect_id
392 + "_" + effect->uniforms_mat3[j].name + ";\n";
396 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
398 string vert_shader = read_version_dependent_file("vs", "vert");
399 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
401 // Collect the resulting program numbers for each uniform.
402 for (unsigned i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
403 Uniform<int> &uniform = phase->uniforms_sampler2d[i];
404 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
406 for (unsigned i = 0; i < phase->uniforms_bool.size(); ++i) {
407 Uniform<bool> &uniform = phase->uniforms_bool[i];
408 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
410 for (unsigned i = 0; i < phase->uniforms_int.size(); ++i) {
411 Uniform<int> &uniform = phase->uniforms_int[i];
412 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
414 for (unsigned i = 0; i < phase->uniforms_float.size(); ++i) {
415 Uniform<float> &uniform = phase->uniforms_float[i];
416 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
418 for (unsigned i = 0; i < phase->uniforms_vec2.size(); ++i) {
419 Uniform<float> &uniform = phase->uniforms_vec2[i];
420 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
422 for (unsigned i = 0; i < phase->uniforms_vec3.size(); ++i) {
423 Uniform<float> &uniform = phase->uniforms_vec3[i];
424 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
426 for (unsigned i = 0; i < phase->uniforms_vec4.size(); ++i) {
427 Uniform<float> &uniform = phase->uniforms_vec4[i];
428 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
430 for (unsigned i = 0; i < phase->uniforms_mat3.size(); ++i) {
431 Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
432 uniform.location = get_uniform_location(phase->glsl_program_num, uniform.prefix, uniform.name);
436 // Construct GLSL programs, starting at the given effect and following
437 // the chain from there. We end a program every time we come to an effect
438 // marked as "needs texture bounce", one that is used by multiple other
439 // effects, every time we need to bounce due to output size change
440 // (not all size changes require ending), and of course at the end.
442 // We follow a quite simple depth-first search from the output, although
443 // without recursing explicitly within each phase.
444 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
446 if (completed_effects->count(output)) {
447 return (*completed_effects)[output];
450 Phase *phase = new Phase;
451 phase->output_node = output;
453 // If the output effect has one-to-one sampling, we try to trace this
454 // status down through the dependency chain. This is important in case
455 // we hit an effect that changes output size (and not sets a virtual
456 // output size); if we have one-to-one sampling, we don't have to break
458 output->one_to_one_sampling = output->effect->one_to_one_sampling();
460 // Effects that we have yet to calculate, but that we know should
461 // be in the current phase.
462 stack<Node *> effects_todo_this_phase;
463 effects_todo_this_phase.push(output);
465 while (!effects_todo_this_phase.empty()) {
466 Node *node = effects_todo_this_phase.top();
467 effects_todo_this_phase.pop();
469 if (node->effect->needs_mipmaps()) {
470 node->needs_mipmaps = true;
473 // This should currently only happen for effects that are inputs
474 // (either true inputs or phase outputs). We special-case inputs,
475 // and then deduplicate phase outputs below.
476 if (node->effect->num_inputs() == 0) {
477 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
481 assert(completed_effects->count(node) == 0);
484 phase->effects.push_back(node);
486 // Find all the dependencies of this effect, and add them to the stack.
487 vector<Node *> deps = node->incoming_links;
488 assert(node->effect->num_inputs() == deps.size());
489 for (unsigned i = 0; i < deps.size(); ++i) {
490 bool start_new_phase = false;
492 if (node->effect->needs_texture_bounce() &&
493 !deps[i]->effect->is_single_texture()) {
494 start_new_phase = true;
497 // Propagate information about needing mipmaps down the chain,
498 // breaking the phase if we notice an incompatibility.
500 // Note that we cannot do this propagation as a normal pass,
501 // because it needs information about where the phases end
502 // (we should not propagate the flag across phases).
503 if (node->needs_mipmaps) {
504 if (deps[i]->effect->num_inputs() == 0) {
505 Input *input = static_cast<Input *>(deps[i]->effect);
506 start_new_phase |= !input->can_supply_mipmaps();
508 deps[i]->needs_mipmaps = true;
512 if (deps[i]->outgoing_links.size() > 1) {
513 if (!deps[i]->effect->is_single_texture()) {
514 // More than one effect uses this as the input,
515 // and it is not a texture itself.
516 // The easiest thing to do (and probably also the safest
517 // performance-wise in most cases) is to bounce it to a texture
518 // and then let the next passes read from that.
519 start_new_phase = true;
521 assert(deps[i]->effect->num_inputs() == 0);
523 // For textures, we try to be slightly more clever;
524 // if none of our outputs need a bounce, we don't bounce
525 // but instead simply use the effect many times.
527 // Strictly speaking, we could bounce it for some outputs
528 // and use it directly for others, but the processing becomes
529 // somewhat simpler if the effect is only used in one such way.
530 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
531 Node *rdep = deps[i]->outgoing_links[j];
532 start_new_phase |= rdep->effect->needs_texture_bounce();
537 if (deps[i]->effect->sets_virtual_output_size()) {
538 assert(deps[i]->effect->changes_output_size());
539 // If the next effect sets a virtual size to rely on OpenGL's
540 // bilinear sampling, we'll really need to break the phase here.
541 start_new_phase = true;
542 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
543 // If the next effect changes size and we don't have one-to-one sampling,
544 // we also need to break here.
545 start_new_phase = true;
548 if (start_new_phase) {
549 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
551 effects_todo_this_phase.push(deps[i]);
553 // Propagate the one-to-one status down through the dependency.
554 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
555 deps[i]->effect->one_to_one_sampling();
560 // No more effects to do this phase. Take all the ones we have,
561 // and create a GLSL program for it.
562 assert(!phase->effects.empty());
564 // Deduplicate the inputs.
565 sort(phase->inputs.begin(), phase->inputs.end());
566 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
568 // Allocate samplers for each input.
569 phase->input_samplers.resize(phase->inputs.size());
571 // We added the effects from the output and back, but we need to output
572 // them in topological sort order in the shader.
573 phase->effects = topological_sort(phase->effects);
575 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
576 phase->input_needs_mipmaps = false;
577 for (unsigned i = 0; i < phase->effects.size(); ++i) {
578 Node *node = phase->effects[i];
579 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
581 for (unsigned i = 0; i < phase->effects.size(); ++i) {
582 Node *node = phase->effects[i];
583 if (node->effect->num_inputs() == 0) {
584 Input *input = static_cast<Input *>(node->effect);
585 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
586 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
590 // Tell each node which phase it ended up in, so that the unit test
591 // can check that the phases were split in the right place.
592 // Note that this ignores that effects may be part of multiple phases;
593 // if the unit tests need to test such cases, we'll reconsider.
594 for (unsigned i = 0; i < phase->effects.size(); ++i) {
595 phase->effects[i]->containing_phase = phase;
598 // Actually make the shader for this phase.
599 compile_glsl_program(phase);
601 // Initialize timer objects.
602 if (movit_timer_queries_supported) {
603 glGenQueries(1, &phase->timer_query_object);
604 phase->time_elapsed_ns = 0;
605 phase->num_measured_iterations = 0;
608 assert(completed_effects->count(output) == 0);
609 completed_effects->insert(make_pair(output, phase));
610 phases.push_back(phase);
614 void EffectChain::output_dot(const char *filename)
616 if (movit_debug_level != MOVIT_DEBUG_ON) {
620 FILE *fp = fopen(filename, "w");
626 fprintf(fp, "digraph G {\n");
627 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
628 for (unsigned i = 0; i < nodes.size(); ++i) {
629 // Find out which phase this event belongs to.
630 vector<int> in_phases;
631 for (unsigned j = 0; j < phases.size(); ++j) {
632 const Phase* p = phases[j];
633 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
634 in_phases.push_back(j);
638 if (in_phases.empty()) {
639 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
640 } else if (in_phases.size() == 1) {
641 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
642 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
643 (in_phases[0] % 8) + 1);
645 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
647 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
648 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
649 (in_phases[0] % 8) + 1);
652 char from_node_id[256];
653 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
655 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
656 char to_node_id[256];
657 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
659 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
660 output_dot_edge(fp, from_node_id, to_node_id, labels);
663 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
665 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
666 output_dot_edge(fp, from_node_id, "output", labels);
674 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
676 vector<string> labels;
678 if (to != NULL && to->effect->needs_texture_bounce()) {
679 labels.push_back("needs_bounce");
681 if (from->effect->changes_output_size()) {
682 labels.push_back("resize");
685 switch (from->output_color_space) {
686 case COLORSPACE_INVALID:
687 labels.push_back("spc[invalid]");
689 case COLORSPACE_REC_601_525:
690 labels.push_back("spc[rec601-525]");
692 case COLORSPACE_REC_601_625:
693 labels.push_back("spc[rec601-625]");
699 switch (from->output_gamma_curve) {
701 labels.push_back("gamma[invalid]");
704 labels.push_back("gamma[sRGB]");
706 case GAMMA_REC_601: // and GAMMA_REC_709
707 labels.push_back("gamma[rec601/709]");
713 switch (from->output_alpha_type) {
715 labels.push_back("alpha[invalid]");
718 labels.push_back("alpha[blank]");
720 case ALPHA_POSTMULTIPLIED:
721 labels.push_back("alpha[postmult]");
730 void EffectChain::output_dot_edge(FILE *fp,
731 const string &from_node_id,
732 const string &to_node_id,
733 const vector<string> &labels)
735 if (labels.empty()) {
736 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
738 string label = labels[0];
739 for (unsigned k = 1; k < labels.size(); ++k) {
740 label += ", " + labels[k];
742 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
746 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
748 unsigned scaled_width, scaled_height;
750 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
751 // Same aspect, or W/H > aspect (image is wider than the frame).
752 // In either case, keep width, and adjust height.
753 scaled_width = width;
754 scaled_height = lrintf(width * aspect_denom / aspect_nom);
756 // W/H < aspect (image is taller than the frame), so keep height,
758 scaled_width = lrintf(height * aspect_nom / aspect_denom);
759 scaled_height = height;
762 // We should be consistently larger or smaller then the existing choice,
763 // since we have the same aspect.
764 assert(!(scaled_width < *output_width && scaled_height > *output_height));
765 assert(!(scaled_height < *output_height && scaled_width > *output_width));
767 if (scaled_width >= *output_width && scaled_height >= *output_height) {
768 *output_width = scaled_width;
769 *output_height = scaled_height;
773 // Propagate input texture sizes throughout, and inform effects downstream.
774 // (Like a lot of other code, we depend on effects being in topological order.)
775 void EffectChain::inform_input_sizes(Phase *phase)
777 // All effects that have a defined size (inputs and RTT inputs)
778 // get that. Reset all others.
779 for (unsigned i = 0; i < phase->effects.size(); ++i) {
780 Node *node = phase->effects[i];
781 if (node->effect->num_inputs() == 0) {
782 Input *input = static_cast<Input *>(node->effect);
783 node->output_width = input->get_width();
784 node->output_height = input->get_height();
785 assert(node->output_width != 0);
786 assert(node->output_height != 0);
788 node->output_width = node->output_height = 0;
791 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
792 Phase *input = phase->inputs[i];
793 input->output_node->output_width = input->virtual_output_width;
794 input->output_node->output_height = input->virtual_output_height;
795 assert(input->output_node->output_width != 0);
796 assert(input->output_node->output_height != 0);
799 // Now propagate from the inputs towards the end, and inform as we go.
800 // The rules are simple:
802 // 1. Don't touch effects that already have given sizes (ie., inputs
803 // or effects that change the output size).
804 // 2. If all of your inputs have the same size, that will be your output size.
805 // 3. Otherwise, your output size is 0x0.
806 for (unsigned i = 0; i < phase->effects.size(); ++i) {
807 Node *node = phase->effects[i];
808 if (node->effect->num_inputs() == 0) {
811 unsigned this_output_width = 0;
812 unsigned this_output_height = 0;
813 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
814 Node *input = node->incoming_links[j];
815 node->effect->inform_input_size(j, input->output_width, input->output_height);
817 this_output_width = input->output_width;
818 this_output_height = input->output_height;
819 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
821 this_output_width = 0;
822 this_output_height = 0;
825 if (node->effect->changes_output_size()) {
826 // We cannot call get_output_size() before we've done inform_input_size()
828 unsigned real_width, real_height;
829 node->effect->get_output_size(&real_width, &real_height,
830 &node->output_width, &node->output_height);
831 assert(node->effect->sets_virtual_output_size() ||
832 (real_width == node->output_width &&
833 real_height == node->output_height));
835 node->output_width = this_output_width;
836 node->output_height = this_output_height;
841 // Note: You should call inform_input_sizes() before this, as the last effect's
842 // desired output size might change based on the inputs.
843 void EffectChain::find_output_size(Phase *phase)
845 Node *output_node = phase->effects.back();
847 // If the last effect explicitly sets an output size, use that.
848 if (output_node->effect->changes_output_size()) {
849 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
850 &phase->virtual_output_width, &phase->virtual_output_height);
851 assert(output_node->effect->sets_virtual_output_size() ||
852 (phase->output_width == phase->virtual_output_width &&
853 phase->output_height == phase->virtual_output_height));
857 // If all effects have the same size, use that.
858 unsigned output_width = 0, output_height = 0;
859 bool all_inputs_same_size = true;
861 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
862 Phase *input = phase->inputs[i];
863 assert(input->output_width != 0);
864 assert(input->output_height != 0);
865 if (output_width == 0 && output_height == 0) {
866 output_width = input->virtual_output_width;
867 output_height = input->virtual_output_height;
868 } else if (output_width != input->virtual_output_width ||
869 output_height != input->virtual_output_height) {
870 all_inputs_same_size = false;
873 for (unsigned i = 0; i < phase->effects.size(); ++i) {
874 Effect *effect = phase->effects[i]->effect;
875 if (effect->num_inputs() != 0) {
879 Input *input = static_cast<Input *>(effect);
880 if (output_width == 0 && output_height == 0) {
881 output_width = input->get_width();
882 output_height = input->get_height();
883 } else if (output_width != input->get_width() ||
884 output_height != input->get_height()) {
885 all_inputs_same_size = false;
889 if (all_inputs_same_size) {
890 assert(output_width != 0);
891 assert(output_height != 0);
892 phase->virtual_output_width = phase->output_width = output_width;
893 phase->virtual_output_height = phase->output_height = output_height;
897 // If not, fit all the inputs into the current aspect, and select the largest one.
900 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
901 Phase *input = phase->inputs[i];
902 assert(input->output_width != 0);
903 assert(input->output_height != 0);
904 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
906 for (unsigned i = 0; i < phase->effects.size(); ++i) {
907 Effect *effect = phase->effects[i]->effect;
908 if (effect->num_inputs() != 0) {
912 Input *input = static_cast<Input *>(effect);
913 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
915 assert(output_width != 0);
916 assert(output_height != 0);
917 phase->virtual_output_width = phase->output_width = output_width;
918 phase->virtual_output_height = phase->output_height = output_height;
921 void EffectChain::sort_all_nodes_topologically()
923 nodes = topological_sort(nodes);
926 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
928 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
929 vector<Node *> sorted_list;
930 for (unsigned i = 0; i < nodes.size(); ++i) {
931 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
933 reverse(sorted_list.begin(), sorted_list.end());
937 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
939 if (nodes_left_to_visit->count(node) == 0) {
942 nodes_left_to_visit->erase(node);
943 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
944 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
946 sorted_list->push_back(node);
949 void EffectChain::find_color_spaces_for_inputs()
951 for (unsigned i = 0; i < nodes.size(); ++i) {
952 Node *node = nodes[i];
953 if (node->disabled) {
956 if (node->incoming_links.size() == 0) {
957 Input *input = static_cast<Input *>(node->effect);
958 node->output_color_space = input->get_color_space();
959 node->output_gamma_curve = input->get_gamma_curve();
961 Effect::AlphaHandling alpha_handling = input->alpha_handling();
962 switch (alpha_handling) {
963 case Effect::OUTPUT_BLANK_ALPHA:
964 node->output_alpha_type = ALPHA_BLANK;
966 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
967 node->output_alpha_type = ALPHA_PREMULTIPLIED;
969 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
970 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
972 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
973 case Effect::DONT_CARE_ALPHA_TYPE:
978 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
979 assert(node->output_gamma_curve == GAMMA_LINEAR);
985 // Propagate gamma and color space information as far as we can in the graph.
986 // The rules are simple: Anything where all the inputs agree, get that as
987 // output as well. Anything else keeps having *_INVALID.
988 void EffectChain::propagate_gamma_and_color_space()
990 // We depend on going through the nodes in order.
991 sort_all_nodes_topologically();
993 for (unsigned i = 0; i < nodes.size(); ++i) {
994 Node *node = nodes[i];
995 if (node->disabled) {
998 assert(node->incoming_links.size() == node->effect->num_inputs());
999 if (node->incoming_links.size() == 0) {
1000 assert(node->output_color_space != COLORSPACE_INVALID);
1001 assert(node->output_gamma_curve != GAMMA_INVALID);
1005 Colorspace color_space = node->incoming_links[0]->output_color_space;
1006 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1007 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1008 if (node->incoming_links[j]->output_color_space != color_space) {
1009 color_space = COLORSPACE_INVALID;
1011 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1012 gamma_curve = GAMMA_INVALID;
1016 // The conversion effects already have their outputs set correctly,
1017 // so leave them alone.
1018 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1019 node->output_color_space = color_space;
1021 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1022 node->effect->effect_type_id() != "GammaExpansionEffect") {
1023 node->output_gamma_curve = gamma_curve;
1028 // Propagate alpha information as far as we can in the graph.
1029 // Similar to propagate_gamma_and_color_space().
1030 void EffectChain::propagate_alpha()
1032 // We depend on going through the nodes in order.
1033 sort_all_nodes_topologically();
1035 for (unsigned i = 0; i < nodes.size(); ++i) {
1036 Node *node = nodes[i];
1037 if (node->disabled) {
1040 assert(node->incoming_links.size() == node->effect->num_inputs());
1041 if (node->incoming_links.size() == 0) {
1042 assert(node->output_alpha_type != ALPHA_INVALID);
1046 // The alpha multiplication/division effects are special cases.
1047 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1048 assert(node->incoming_links.size() == 1);
1049 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1050 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1053 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1054 assert(node->incoming_links.size() == 1);
1055 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1056 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1060 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1061 // because they are the only one that _need_ postmultiplied alpha.
1062 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1063 node->effect->effect_type_id() == "GammaExpansionEffect") {
1064 assert(node->incoming_links.size() == 1);
1065 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1066 node->output_alpha_type = ALPHA_BLANK;
1067 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1068 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1070 node->output_alpha_type = ALPHA_INVALID;
1075 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1076 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1077 // taken care of above. Rationale: Even if you could imagine
1078 // e.g. an effect that took in an image and set alpha=1.0
1079 // unconditionally, it wouldn't make any sense to have it as
1080 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1081 // got its input pre- or postmultiplied, so it wouldn't know
1082 // whether to divide away the old alpha or not.
1083 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1084 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1085 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1086 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1088 // If the node has multiple inputs, check that they are all valid and
1090 bool any_invalid = false;
1091 bool any_premultiplied = false;
1092 bool any_postmultiplied = false;
1094 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1095 switch (node->incoming_links[j]->output_alpha_type) {
1100 // Blank is good as both pre- and postmultiplied alpha,
1101 // so just ignore it.
1103 case ALPHA_PREMULTIPLIED:
1104 any_premultiplied = true;
1106 case ALPHA_POSTMULTIPLIED:
1107 any_postmultiplied = true;
1115 node->output_alpha_type = ALPHA_INVALID;
1119 // Inputs must be of the same type.
1120 if (any_premultiplied && any_postmultiplied) {
1121 node->output_alpha_type = ALPHA_INVALID;
1125 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1126 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1127 // If the effect has asked for premultiplied alpha, check that it has got it.
1128 if (any_postmultiplied) {
1129 node->output_alpha_type = ALPHA_INVALID;
1130 } else if (!any_premultiplied &&
1131 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1132 // Blank input alpha, and the effect preserves blank alpha.
1133 node->output_alpha_type = ALPHA_BLANK;
1135 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1138 // OK, all inputs are the same, and this effect is not going
1140 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1141 if (any_premultiplied) {
1142 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1143 } else if (any_postmultiplied) {
1144 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1146 node->output_alpha_type = ALPHA_BLANK;
1152 bool EffectChain::node_needs_colorspace_fix(Node *node)
1154 if (node->disabled) {
1157 if (node->effect->num_inputs() == 0) {
1161 // propagate_gamma_and_color_space() has already set our output
1162 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1163 if (node->output_color_space == COLORSPACE_INVALID) {
1166 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1169 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1170 // the graph. Our strategy is not always optimal, but quite simple:
1171 // Find an effect that's as early as possible where the inputs are of
1172 // unacceptable colorspaces (that is, either different, or, if the effect only
1173 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1174 // propagate the information anew, and repeat until there are no more such
1176 void EffectChain::fix_internal_color_spaces()
1178 unsigned colorspace_propagation_pass = 0;
1182 for (unsigned i = 0; i < nodes.size(); ++i) {
1183 Node *node = nodes[i];
1184 if (!node_needs_colorspace_fix(node)) {
1188 // Go through each input that is not sRGB, and insert
1189 // a colorspace conversion after it.
1190 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1191 Node *input = node->incoming_links[j];
1192 assert(input->output_color_space != COLORSPACE_INVALID);
1193 if (input->output_color_space == COLORSPACE_sRGB) {
1196 Node *conversion = add_node(new ColorspaceConversionEffect());
1197 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1198 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1199 conversion->output_color_space = COLORSPACE_sRGB;
1200 replace_sender(input, conversion);
1201 connect_nodes(input, conversion);
1204 // Re-sort topologically, and propagate the new information.
1205 propagate_gamma_and_color_space();
1212 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1213 output_dot(filename);
1214 assert(colorspace_propagation_pass < 100);
1215 } while (found_any);
1217 for (unsigned i = 0; i < nodes.size(); ++i) {
1218 Node *node = nodes[i];
1219 if (node->disabled) {
1222 assert(node->output_color_space != COLORSPACE_INVALID);
1226 bool EffectChain::node_needs_alpha_fix(Node *node)
1228 if (node->disabled) {
1232 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1233 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1234 return (node->output_alpha_type == ALPHA_INVALID);
1237 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1238 // the graph. Similar to fix_internal_color_spaces().
1239 void EffectChain::fix_internal_alpha(unsigned step)
1241 unsigned alpha_propagation_pass = 0;
1245 for (unsigned i = 0; i < nodes.size(); ++i) {
1246 Node *node = nodes[i];
1247 if (!node_needs_alpha_fix(node)) {
1251 // If we need to fix up GammaExpansionEffect, then clearly something
1252 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1254 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1256 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1258 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1259 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1260 assert(node->incoming_links.size() == 1);
1261 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1262 desired_type = ALPHA_POSTMULTIPLIED;
1265 // Go through each input that is not premultiplied alpha, and insert
1266 // a conversion before it.
1267 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1268 Node *input = node->incoming_links[j];
1269 assert(input->output_alpha_type != ALPHA_INVALID);
1270 if (input->output_alpha_type == desired_type ||
1271 input->output_alpha_type == ALPHA_BLANK) {
1275 if (desired_type == ALPHA_PREMULTIPLIED) {
1276 conversion = add_node(new AlphaMultiplicationEffect());
1278 conversion = add_node(new AlphaDivisionEffect());
1280 conversion->output_alpha_type = desired_type;
1281 replace_sender(input, conversion);
1282 connect_nodes(input, conversion);
1285 // Re-sort topologically, and propagate the new information.
1286 propagate_gamma_and_color_space();
1294 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1295 output_dot(filename);
1296 assert(alpha_propagation_pass < 100);
1297 } while (found_any);
1299 for (unsigned i = 0; i < nodes.size(); ++i) {
1300 Node *node = nodes[i];
1301 if (node->disabled) {
1304 assert(node->output_alpha_type != ALPHA_INVALID);
1308 // Make so that the output is in the desired color space.
1309 void EffectChain::fix_output_color_space()
1311 Node *output = find_output_node();
1312 if (output->output_color_space != output_format.color_space) {
1313 Node *conversion = add_node(new ColorspaceConversionEffect());
1314 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1315 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1316 conversion->output_color_space = output_format.color_space;
1317 connect_nodes(output, conversion);
1319 propagate_gamma_and_color_space();
1323 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1324 void EffectChain::fix_output_alpha()
1326 Node *output = find_output_node();
1327 assert(output->output_alpha_type != ALPHA_INVALID);
1328 if (output->output_alpha_type == ALPHA_BLANK) {
1329 // No alpha output, so we don't care.
1332 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1333 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1334 Node *conversion = add_node(new AlphaDivisionEffect());
1335 connect_nodes(output, conversion);
1337 propagate_gamma_and_color_space();
1339 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1340 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1341 Node *conversion = add_node(new AlphaMultiplicationEffect());
1342 connect_nodes(output, conversion);
1344 propagate_gamma_and_color_space();
1348 bool EffectChain::node_needs_gamma_fix(Node *node)
1350 if (node->disabled) {
1354 // Small hack since the output is not an explicit node:
1355 // If we are the last node and our output is in the wrong
1356 // space compared to EffectChain's output, we need to fix it.
1357 // This will only take us to linear, but fix_output_gamma()
1358 // will come and take us to the desired output gamma
1361 // This needs to be before everything else, since it could
1362 // even apply to inputs (if they are the only effect).
1363 if (node->outgoing_links.empty() &&
1364 node->output_gamma_curve != output_format.gamma_curve &&
1365 node->output_gamma_curve != GAMMA_LINEAR) {
1369 if (node->effect->num_inputs() == 0) {
1373 // propagate_gamma_and_color_space() has already set our output
1374 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1375 // except for GammaCompressionEffect.
1376 if (node->output_gamma_curve == GAMMA_INVALID) {
1379 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1380 assert(node->incoming_links.size() == 1);
1381 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1384 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1387 // Very similar to fix_internal_color_spaces(), but for gamma.
1388 // There is one difference, though; before we start adding conversion nodes,
1389 // we see if we can get anything out of asking the sources to deliver
1390 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1391 // does that part, while fix_internal_gamma_by_inserting_nodes()
1392 // inserts nodes as needed afterwards.
1393 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1395 unsigned gamma_propagation_pass = 0;
1399 for (unsigned i = 0; i < nodes.size(); ++i) {
1400 Node *node = nodes[i];
1401 if (!node_needs_gamma_fix(node)) {
1405 // See if all inputs can give us linear gamma. If not, leave it.
1406 vector<Node *> nonlinear_inputs;
1407 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1408 assert(!nonlinear_inputs.empty());
1411 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1412 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1413 all_ok &= input->can_output_linear_gamma();
1420 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1421 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1422 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1425 // Re-sort topologically, and propagate the new information.
1426 propagate_gamma_and_color_space();
1433 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1434 output_dot(filename);
1435 assert(gamma_propagation_pass < 100);
1436 } while (found_any);
1439 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1441 unsigned gamma_propagation_pass = 0;
1445 for (unsigned i = 0; i < nodes.size(); ++i) {
1446 Node *node = nodes[i];
1447 if (!node_needs_gamma_fix(node)) {
1451 // Special case: We could be an input and still be asked to
1452 // fix our gamma; if so, we should be the only node
1453 // (as node_needs_gamma_fix() would only return true in
1454 // for an input in that case). That means we should insert
1455 // a conversion node _after_ ourselves.
1456 if (node->incoming_links.empty()) {
1457 assert(node->outgoing_links.empty());
1458 Node *conversion = add_node(new GammaExpansionEffect());
1459 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1460 conversion->output_gamma_curve = GAMMA_LINEAR;
1461 connect_nodes(node, conversion);
1464 // If not, go through each input that is not linear gamma,
1465 // and insert a gamma conversion after it.
1466 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1467 Node *input = node->incoming_links[j];
1468 assert(input->output_gamma_curve != GAMMA_INVALID);
1469 if (input->output_gamma_curve == GAMMA_LINEAR) {
1472 Node *conversion = add_node(new GammaExpansionEffect());
1473 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1474 conversion->output_gamma_curve = GAMMA_LINEAR;
1475 replace_sender(input, conversion);
1476 connect_nodes(input, conversion);
1479 // Re-sort topologically, and propagate the new information.
1481 propagate_gamma_and_color_space();
1488 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1489 output_dot(filename);
1490 assert(gamma_propagation_pass < 100);
1491 } while (found_any);
1493 for (unsigned i = 0; i < nodes.size(); ++i) {
1494 Node *node = nodes[i];
1495 if (node->disabled) {
1498 assert(node->output_gamma_curve != GAMMA_INVALID);
1502 // Make so that the output is in the desired gamma.
1503 // Note that this assumes linear input gamma, so it might create the need
1504 // for another pass of fix_internal_gamma().
1505 void EffectChain::fix_output_gamma()
1507 Node *output = find_output_node();
1508 if (output->output_gamma_curve != output_format.gamma_curve) {
1509 Node *conversion = add_node(new GammaCompressionEffect());
1510 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1511 conversion->output_gamma_curve = output_format.gamma_curve;
1512 connect_nodes(output, conversion);
1516 // If the user has requested Y'CbCr output, we need to do this conversion
1517 // _after_ GammaCompressionEffect etc., but before dither (see below).
1518 // This is because Y'CbCr, with the exception of a special optional mode
1519 // in Rec. 2020 (which we currently don't support), is defined to work on
1520 // gamma-encoded data.
1521 void EffectChain::add_ycbcr_conversion_if_needed()
1523 assert(output_color_type == OUTPUT_COLOR_RGB || output_color_type == OUTPUT_COLOR_YCBCR);
1524 if (output_color_type != OUTPUT_COLOR_YCBCR) {
1527 Node *output = find_output_node();
1528 Node *ycbcr = add_node(new YCbCrConversionEffect(output_ycbcr_format));
1529 connect_nodes(output, ycbcr);
1532 // If the user has requested dither, add a DitherEffect right at the end
1533 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1534 // since dither is about the only effect that can _not_ be done in linear space.
1535 void EffectChain::add_dither_if_needed()
1537 if (num_dither_bits == 0) {
1540 Node *output = find_output_node();
1541 Node *dither = add_node(new DitherEffect());
1542 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1543 connect_nodes(output, dither);
1545 dither_effect = dither->effect;
1548 // Find the output node. This is, simply, one that has no outgoing links.
1549 // If there are multiple ones, the graph is malformed (we do not support
1550 // multiple outputs right now).
1551 Node *EffectChain::find_output_node()
1553 vector<Node *> output_nodes;
1554 for (unsigned i = 0; i < nodes.size(); ++i) {
1555 Node *node = nodes[i];
1556 if (node->disabled) {
1559 if (node->outgoing_links.empty()) {
1560 output_nodes.push_back(node);
1563 assert(output_nodes.size() == 1);
1564 return output_nodes[0];
1567 void EffectChain::finalize()
1569 // Output the graph as it is before we do any conversions on it.
1570 output_dot("step0-start.dot");
1572 // Give each effect in turn a chance to rewrite its own part of the graph.
1573 // Note that if more effects are added as part of this, they will be
1574 // picked up as part of the same for loop, since they are added at the end.
1575 for (unsigned i = 0; i < nodes.size(); ++i) {
1576 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1578 output_dot("step1-rewritten.dot");
1580 find_color_spaces_for_inputs();
1581 output_dot("step2-input-colorspace.dot");
1584 output_dot("step3-propagated-alpha.dot");
1586 propagate_gamma_and_color_space();
1587 output_dot("step4-propagated-all.dot");
1589 fix_internal_color_spaces();
1590 fix_internal_alpha(6);
1591 fix_output_color_space();
1592 output_dot("step7-output-colorspacefix.dot");
1594 output_dot("step8-output-alphafix.dot");
1596 // Note that we need to fix gamma after colorspace conversion,
1597 // because colorspace conversions might create needs for gamma conversions.
1598 // Also, we need to run an extra pass of fix_internal_gamma() after
1599 // fixing the output gamma, as we only have conversions to/from linear,
1600 // and fix_internal_alpha() since GammaCompressionEffect needs
1601 // postmultiplied input.
1602 fix_internal_gamma_by_asking_inputs(9);
1603 fix_internal_gamma_by_inserting_nodes(10);
1605 output_dot("step11-output-gammafix.dot");
1607 output_dot("step12-output-alpha-propagated.dot");
1608 fix_internal_alpha(13);
1609 output_dot("step14-output-alpha-fixed.dot");
1610 fix_internal_gamma_by_asking_inputs(15);
1611 fix_internal_gamma_by_inserting_nodes(16);
1613 output_dot("step17-before-ycbcr.dot");
1614 add_ycbcr_conversion_if_needed();
1616 output_dot("step18-before-dither.dot");
1617 add_dither_if_needed();
1619 output_dot("step19-final.dot");
1621 // Construct all needed GLSL programs, starting at the output.
1622 // We need to keep track of which effects have already been computed,
1623 // as an effect with multiple users could otherwise be calculated
1625 map<Node *, Phase *> completed_effects;
1626 construct_phase(find_output_node(), &completed_effects);
1628 output_dot("step20-split-to-phases.dot");
1630 assert(phases[0]->inputs.empty());
1635 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1639 // Save original viewport.
1640 GLuint x = 0, y = 0;
1642 if (width == 0 && height == 0) {
1644 glGetIntegerv(GL_VIEWPORT, viewport);
1647 width = viewport[2];
1648 height = viewport[3];
1652 glDisable(GL_BLEND);
1654 glDisable(GL_DEPTH_TEST);
1656 glDepthMask(GL_FALSE);
1659 set<Phase *> generated_mipmaps;
1661 // We choose the simplest option of having one texture per output,
1662 // since otherwise this turns into an (albeit simple) register allocation problem.
1663 map<Phase *, GLuint> output_textures;
1665 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1666 Phase *phase = phases[phase_num];
1668 if (do_phase_timing) {
1669 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1671 if (phase_num == phases.size() - 1) {
1672 // Last phase goes to the output the user specified.
1673 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1675 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1676 assert(status == GL_FRAMEBUFFER_COMPLETE);
1677 glViewport(x, y, width, height);
1678 if (dither_effect != NULL) {
1679 CHECK(dither_effect->set_int("output_width", width));
1680 CHECK(dither_effect->set_int("output_height", height));
1683 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1684 if (do_phase_timing) {
1685 glEndQuery(GL_TIME_ELAPSED);
1689 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1690 texture_it != output_textures.end();
1692 resource_pool->release_2d_texture(texture_it->second);
1695 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1700 if (do_phase_timing) {
1701 // Get back the timer queries.
1702 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1703 Phase *phase = phases[phase_num];
1704 GLint available = 0;
1705 while (!available) {
1706 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1708 GLuint64 time_elapsed;
1709 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1710 phase->time_elapsed_ns += time_elapsed;
1711 ++phase->num_measured_iterations;
1716 void EffectChain::enable_phase_timing(bool enable)
1719 assert(movit_timer_queries_supported);
1721 this->do_phase_timing = enable;
1724 void EffectChain::reset_phase_timing()
1726 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1727 Phase *phase = phases[phase_num];
1728 phase->time_elapsed_ns = 0;
1729 phase->num_measured_iterations = 0;
1733 void EffectChain::print_phase_timing()
1735 double total_time_ms = 0.0;
1736 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1737 Phase *phase = phases[phase_num];
1738 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1739 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1740 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1741 if (effect_num != 0) {
1744 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1747 total_time_ms += avg_time_ms;
1749 printf("Total: %5.1f ms\n", total_time_ms);
1752 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1756 // Find a texture for this phase.
1757 inform_input_sizes(phase);
1759 find_output_size(phase);
1761 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1762 output_textures->insert(make_pair(phase, tex_num));
1765 const GLuint glsl_program_num = phase->glsl_program_num;
1767 glUseProgram(glsl_program_num);
1770 // Set up RTT inputs for this phase.
1771 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1772 glActiveTexture(GL_TEXTURE0 + sampler);
1773 Phase *input = phase->inputs[sampler];
1774 input->output_node->bound_sampler_num = sampler;
1775 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1777 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1778 glGenerateMipmap(GL_TEXTURE_2D);
1780 generated_mipmaps->insert(input);
1782 setup_rtt_sampler(sampler, phase->input_needs_mipmaps);
1783 phase->input_samplers[sampler] = sampler; // Bind the sampler to the right uniform.
1786 // And now the output. (Already set up for us if it is the last phase.)
1788 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1789 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1790 glViewport(0, 0, phase->output_width, phase->output_height);
1793 // Give the required parameters to all the effects.
1794 unsigned sampler_num = phase->inputs.size();
1795 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1796 Node *node = phase->effects[i];
1797 unsigned old_sampler_num = sampler_num;
1798 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1801 if (node->effect->is_single_texture()) {
1802 assert(sampler_num - old_sampler_num == 1);
1803 node->bound_sampler_num = old_sampler_num;
1805 node->bound_sampler_num = -1;
1809 // Uniforms need to come after set_gl_state(), since they can be updated
1811 setup_uniforms(phase);
1814 float vertices[] = {
1821 glGenVertexArrays(1, &vao);
1823 glBindVertexArray(vao);
1826 GLuint position_vbo = fill_vertex_attribute(glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1827 GLuint texcoord_vbo = fill_vertex_attribute(glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1829 glDrawArrays(GL_TRIANGLES, 0, 3);
1832 cleanup_vertex_attribute(glsl_program_num, "position", position_vbo);
1833 cleanup_vertex_attribute(glsl_program_num, "texcoord", texcoord_vbo);
1838 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1839 Node *node = phase->effects[i];
1840 node->effect->clear_gl_state();
1844 resource_pool->release_fbo(fbo);
1847 glDeleteVertexArrays(1, &vao);
1851 void EffectChain::setup_uniforms(Phase *phase)
1853 // TODO: Use UBO blocks.
1854 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
1855 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
1856 if (uniform.location != -1) {
1857 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1860 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
1861 const Uniform<bool> &uniform = phase->uniforms_bool[i];
1862 assert(uniform.num_values == 1);
1863 if (uniform.location != -1) {
1864 glUniform1i(uniform.location, *uniform.value);
1867 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
1868 const Uniform<int> &uniform = phase->uniforms_int[i];
1869 if (uniform.location != -1) {
1870 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1873 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
1874 const Uniform<float> &uniform = phase->uniforms_float[i];
1875 if (uniform.location != -1) {
1876 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
1879 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
1880 const Uniform<float> &uniform = phase->uniforms_vec2[i];
1881 if (uniform.location != -1) {
1882 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
1885 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
1886 const Uniform<float> &uniform = phase->uniforms_vec3[i];
1887 if (uniform.location != -1) {
1888 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
1891 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
1892 const Uniform<float> &uniform = phase->uniforms_vec4[i];
1893 if (uniform.location != -1) {
1894 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
1897 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
1898 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
1899 assert(uniform.num_values == 1);
1900 if (uniform.location != -1) {
1901 // Convert to float (GLSL has no double matrices).
1903 for (unsigned y = 0; y < 3; ++y) {
1904 for (unsigned x = 0; x < 3; ++x) {
1905 matrixf[y + x * 3] = (*uniform.value)(y, x);
1908 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
1913 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
1915 glActiveTexture(GL_TEXTURE0 + sampler_num);
1918 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1921 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1924 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1926 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1930 } // namespace movit