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),
40 output_color_rgba(false),
41 output_color_ycbcr(false),
44 output_origin(OUTPUT_ORIGIN_BOTTOM_LEFT),
46 resource_pool(resource_pool),
47 do_phase_timing(false) {
48 if (resource_pool == NULL) {
49 this->resource_pool = new ResourcePool();
50 owns_resource_pool = true;
52 owns_resource_pool = false;
56 EffectChain::~EffectChain()
58 for (unsigned i = 0; i < nodes.size(); ++i) {
59 delete nodes[i]->effect;
62 for (unsigned i = 0; i < phases.size(); ++i) {
63 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
66 if (owns_resource_pool) {
71 Input *EffectChain::add_input(Input *input)
74 inputs.push_back(input);
79 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
82 assert(!output_color_rgba);
83 output_format = format;
84 output_alpha_format = alpha_format;
85 output_color_rgba = true;
88 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
89 const YCbCrFormat &ycbcr_format, YCbCrOutputSplitting output_splitting)
92 assert(!output_color_ycbcr);
93 output_format = format;
94 output_alpha_format = alpha_format;
95 output_color_ycbcr = true;
96 output_ycbcr_format = ycbcr_format;
97 output_ycbcr_splitting = output_splitting;
99 assert(ycbcr_format.chroma_subsampling_x == 1);
100 assert(ycbcr_format.chroma_subsampling_y == 1);
103 Node *EffectChain::add_node(Effect *effect)
105 for (unsigned i = 0; i < nodes.size(); ++i) {
106 assert(nodes[i]->effect != effect);
109 Node *node = new Node;
110 node->effect = effect;
111 node->disabled = false;
112 node->output_color_space = COLORSPACE_INVALID;
113 node->output_gamma_curve = GAMMA_INVALID;
114 node->output_alpha_type = ALPHA_INVALID;
115 node->needs_mipmaps = false;
116 node->one_to_one_sampling = false;
118 nodes.push_back(node);
119 node_map[effect] = node;
120 effect->inform_added(this);
124 void EffectChain::connect_nodes(Node *sender, Node *receiver)
126 sender->outgoing_links.push_back(receiver);
127 receiver->incoming_links.push_back(sender);
130 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
132 new_receiver->incoming_links = old_receiver->incoming_links;
133 old_receiver->incoming_links.clear();
135 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
136 Node *sender = new_receiver->incoming_links[i];
137 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
138 if (sender->outgoing_links[j] == old_receiver) {
139 sender->outgoing_links[j] = new_receiver;
145 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
147 new_sender->outgoing_links = old_sender->outgoing_links;
148 old_sender->outgoing_links.clear();
150 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
151 Node *receiver = new_sender->outgoing_links[i];
152 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
153 if (receiver->incoming_links[j] == old_sender) {
154 receiver->incoming_links[j] = new_sender;
160 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
162 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
163 if (sender->outgoing_links[i] == receiver) {
164 sender->outgoing_links[i] = middle;
165 middle->incoming_links.push_back(sender);
168 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
169 if (receiver->incoming_links[i] == sender) {
170 receiver->incoming_links[i] = middle;
171 middle->outgoing_links.push_back(receiver);
175 assert(middle->incoming_links.size() == middle->effect->num_inputs());
178 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
180 assert(node->effect->needs_texture_bounce());
181 assert(input_num < node->incoming_links.size());
182 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
183 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
184 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
187 GLenum EffectChain::has_input_sampler(Node *node, unsigned input_num) const
189 assert(input_num < node->incoming_links.size());
190 return node->incoming_links[input_num]->bound_sampler_num >= 0 &&
191 node->incoming_links[input_num]->bound_sampler_num < 8;
194 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
196 if (node->output_gamma_curve == GAMMA_LINEAR &&
197 node->effect->effect_type_id() != "GammaCompressionEffect") {
200 if (node->effect->num_inputs() == 0) {
201 nonlinear_inputs->push_back(node);
203 assert(node->effect->num_inputs() == node->incoming_links.size());
204 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
205 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
210 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
213 assert(inputs.size() == effect->num_inputs());
214 Node *node = add_node(effect);
215 for (unsigned i = 0; i < inputs.size(); ++i) {
216 assert(node_map.count(inputs[i]) != 0);
217 connect_nodes(node_map[inputs[i]], node);
222 // ESSL doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
223 string replace_prefix(const string &text, const string &prefix)
228 while (start < text.size()) {
229 size_t pos = text.find("PREFIX(", start);
230 if (pos == string::npos) {
231 output.append(text.substr(start, string::npos));
235 output.append(text.substr(start, pos - start));
236 output.append(prefix);
239 pos += strlen("PREFIX(");
241 // Output stuff until we find the matching ), which we then eat.
243 size_t end_arg_pos = pos;
244 while (end_arg_pos < text.size()) {
245 if (text[end_arg_pos] == '(') {
247 } else if (text[end_arg_pos] == ')') {
255 output.append(text.substr(pos, end_arg_pos - pos));
266 void extract_uniform_declarations(const vector<Uniform<T> > &effect_uniforms,
267 const string &type_specifier,
268 const string &effect_id,
269 vector<Uniform<T> > *phase_uniforms,
272 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
273 phase_uniforms->push_back(effect_uniforms[i]);
274 phase_uniforms->back().prefix = effect_id;
276 *glsl_string += string("uniform ") + type_specifier + " " + effect_id
277 + "_" + effect_uniforms[i].name + ";\n";
282 void extract_uniform_array_declarations(const vector<Uniform<T> > &effect_uniforms,
283 const string &type_specifier,
284 const string &effect_id,
285 vector<Uniform<T> > *phase_uniforms,
288 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
289 phase_uniforms->push_back(effect_uniforms[i]);
290 phase_uniforms->back().prefix = effect_id;
293 snprintf(buf, sizeof(buf), "uniform %s %s_%s[%d];\n",
294 type_specifier.c_str(), effect_id.c_str(),
295 effect_uniforms[i].name.c_str(),
296 int(effect_uniforms[i].num_values));
302 void collect_uniform_locations(GLuint glsl_program_num, vector<Uniform<T> > *phase_uniforms)
304 for (unsigned i = 0; i < phase_uniforms->size(); ++i) {
305 Uniform<T> &uniform = (*phase_uniforms)[i];
306 uniform.location = get_uniform_location(glsl_program_num, uniform.prefix, uniform.name);
312 void EffectChain::compile_glsl_program(Phase *phase)
314 string frag_shader_header = read_version_dependent_file("header", "frag");
315 string frag_shader = "";
317 // Create functions and uniforms for all the texture inputs that we need.
318 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
319 Node *input = phase->inputs[i]->output_node;
321 sprintf(effect_id, "in%u", i);
322 phase->effect_ids.insert(make_pair(input, effect_id));
324 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
325 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
326 frag_shader += "\treturn tex2D(tex_" + string(effect_id) + ", tc);\n";
327 frag_shader += "}\n";
330 Uniform<int> uniform;
331 uniform.name = effect_id;
332 uniform.value = &phase->input_samplers[i];
333 uniform.prefix = "tex";
334 uniform.num_values = 1;
335 uniform.location = -1;
336 phase->uniforms_sampler2d.push_back(uniform);
339 // Give each effect in the phase its own ID.
340 for (unsigned i = 0; i < phase->effects.size(); ++i) {
341 Node *node = phase->effects[i];
343 sprintf(effect_id, "eff%u", i);
344 phase->effect_ids.insert(make_pair(node, effect_id));
347 for (unsigned i = 0; i < phase->effects.size(); ++i) {
348 Node *node = phase->effects[i];
349 const string effect_id = phase->effect_ids[node];
350 if (node->incoming_links.size() == 1) {
351 frag_shader += string("#define INPUT ") + phase->effect_ids[node->incoming_links[0]] + "\n";
353 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
355 sprintf(buf, "#define INPUT%d %s\n", j + 1, phase->effect_ids[node->incoming_links[j]].c_str());
361 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
362 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
363 frag_shader += "#undef PREFIX\n";
364 frag_shader += "#undef FUNCNAME\n";
365 if (node->incoming_links.size() == 1) {
366 frag_shader += "#undef INPUT\n";
368 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
370 sprintf(buf, "#undef INPUT%d\n", j + 1);
376 frag_shader += string("#define INPUT ") + phase->effect_ids[phase->effects.back()] + "\n";
378 // If we're the last phase, add the right #defines for Y'CbCr multi-output as needed.
379 if (phase->output_node->outgoing_links.empty() && output_color_ycbcr) {
380 switch (output_ycbcr_splitting) {
381 case YCBCR_OUTPUT_INTERLEAVED:
384 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
385 frag_shader += "#define YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
387 case YCBCR_OUTPUT_PLANAR:
388 frag_shader += "#define YCBCR_OUTPUT_PLANAR 1\n";
394 if (output_color_rgba) {
395 // Note: Needs to come in the header, because not only the
396 // output needs to see it (YCbCrConversionEffect and DitherEffect
398 frag_shader_header += "#define YCBCR_ALSO_OUTPUT_RGBA 1\n";
401 frag_shader.append(read_file("footer.frag"));
403 // Collect uniforms from all effects and output them. Note that this needs
404 // to happen after output_fragment_shader(), even though the uniforms come
405 // before in the output source, since output_fragment_shader() is allowed
406 // to register new uniforms (e.g. arrays that are of unknown length until
407 // finalization time).
408 // TODO: Make a uniform block for platforms that support it.
409 string frag_shader_uniforms = "";
410 for (unsigned i = 0; i < phase->effects.size(); ++i) {
411 Node *node = phase->effects[i];
412 Effect *effect = node->effect;
413 const string effect_id = phase->effect_ids[node];
414 extract_uniform_declarations(effect->uniforms_sampler2d, "sampler2D", effect_id, &phase->uniforms_sampler2d, &frag_shader_uniforms);
415 extract_uniform_declarations(effect->uniforms_bool, "bool", effect_id, &phase->uniforms_bool, &frag_shader_uniforms);
416 extract_uniform_declarations(effect->uniforms_int, "int", effect_id, &phase->uniforms_int, &frag_shader_uniforms);
417 extract_uniform_declarations(effect->uniforms_float, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
418 extract_uniform_declarations(effect->uniforms_vec2, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
419 extract_uniform_declarations(effect->uniforms_vec3, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
420 extract_uniform_declarations(effect->uniforms_vec4, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
421 extract_uniform_array_declarations(effect->uniforms_float_array, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
422 extract_uniform_array_declarations(effect->uniforms_vec2_array, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
423 extract_uniform_array_declarations(effect->uniforms_vec3_array, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
424 extract_uniform_array_declarations(effect->uniforms_vec4_array, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
425 extract_uniform_declarations(effect->uniforms_mat3, "mat3", effect_id, &phase->uniforms_mat3, &frag_shader_uniforms);
428 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
430 string vert_shader = read_version_dependent_file("vs", "vert");
432 // If we're the last phase and need to flip the picture to compensate for
433 // the origin, tell the vertex shader so.
434 if (phase->output_node->outgoing_links.empty() && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
435 const string needle = "#define FLIP_ORIGIN 0";
436 size_t pos = vert_shader.find(needle);
437 assert(pos != string::npos);
439 vert_shader[pos + needle.size() - 1] = '1';
442 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader);
444 // Collect the resulting location numbers for each uniform.
445 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
446 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
447 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
448 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
449 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
450 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
451 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
452 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
455 // Construct GLSL programs, starting at the given effect and following
456 // the chain from there. We end a program every time we come to an effect
457 // marked as "needs texture bounce", one that is used by multiple other
458 // effects, every time we need to bounce due to output size change
459 // (not all size changes require ending), and of course at the end.
461 // We follow a quite simple depth-first search from the output, although
462 // without recursing explicitly within each phase.
463 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
465 if (completed_effects->count(output)) {
466 return (*completed_effects)[output];
469 Phase *phase = new Phase;
470 phase->output_node = output;
472 // If the output effect has one-to-one sampling, we try to trace this
473 // status down through the dependency chain. This is important in case
474 // we hit an effect that changes output size (and not sets a virtual
475 // output size); if we have one-to-one sampling, we don't have to break
477 output->one_to_one_sampling = output->effect->one_to_one_sampling();
479 // Effects that we have yet to calculate, but that we know should
480 // be in the current phase.
481 stack<Node *> effects_todo_this_phase;
482 effects_todo_this_phase.push(output);
484 while (!effects_todo_this_phase.empty()) {
485 Node *node = effects_todo_this_phase.top();
486 effects_todo_this_phase.pop();
488 if (node->effect->needs_mipmaps()) {
489 node->needs_mipmaps = true;
492 // This should currently only happen for effects that are inputs
493 // (either true inputs or phase outputs). We special-case inputs,
494 // and then deduplicate phase outputs below.
495 if (node->effect->num_inputs() == 0) {
496 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
500 assert(completed_effects->count(node) == 0);
503 phase->effects.push_back(node);
505 // Find all the dependencies of this effect, and add them to the stack.
506 vector<Node *> deps = node->incoming_links;
507 assert(node->effect->num_inputs() == deps.size());
508 for (unsigned i = 0; i < deps.size(); ++i) {
509 bool start_new_phase = false;
511 if (node->effect->needs_texture_bounce() &&
512 !deps[i]->effect->is_single_texture() &&
513 !deps[i]->effect->override_disable_bounce()) {
514 start_new_phase = true;
517 // Propagate information about needing mipmaps down the chain,
518 // breaking the phase if we notice an incompatibility.
520 // Note that we cannot do this propagation as a normal pass,
521 // because it needs information about where the phases end
522 // (we should not propagate the flag across phases).
523 if (node->needs_mipmaps) {
524 if (deps[i]->effect->num_inputs() == 0) {
525 Input *input = static_cast<Input *>(deps[i]->effect);
526 start_new_phase |= !input->can_supply_mipmaps();
528 deps[i]->needs_mipmaps = true;
532 if (deps[i]->outgoing_links.size() > 1) {
533 if (!deps[i]->effect->is_single_texture()) {
534 // More than one effect uses this as the input,
535 // and it is not a texture itself.
536 // The easiest thing to do (and probably also the safest
537 // performance-wise in most cases) is to bounce it to a texture
538 // and then let the next passes read from that.
539 start_new_phase = true;
541 assert(deps[i]->effect->num_inputs() == 0);
543 // For textures, we try to be slightly more clever;
544 // if none of our outputs need a bounce, we don't bounce
545 // but instead simply use the effect many times.
547 // Strictly speaking, we could bounce it for some outputs
548 // and use it directly for others, but the processing becomes
549 // somewhat simpler if the effect is only used in one such way.
550 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
551 Node *rdep = deps[i]->outgoing_links[j];
552 start_new_phase |= rdep->effect->needs_texture_bounce();
557 if (deps[i]->effect->sets_virtual_output_size()) {
558 assert(deps[i]->effect->changes_output_size());
559 // If the next effect sets a virtual size to rely on OpenGL's
560 // bilinear sampling, we'll really need to break the phase here.
561 start_new_phase = true;
562 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
563 // If the next effect changes size and we don't have one-to-one sampling,
564 // we also need to break here.
565 start_new_phase = true;
568 if (start_new_phase) {
569 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
571 effects_todo_this_phase.push(deps[i]);
573 // Propagate the one-to-one status down through the dependency.
574 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
575 deps[i]->effect->one_to_one_sampling();
580 // No more effects to do this phase. Take all the ones we have,
581 // and create a GLSL program for it.
582 assert(!phase->effects.empty());
584 // Deduplicate the inputs.
585 sort(phase->inputs.begin(), phase->inputs.end());
586 phase->inputs.erase(unique(phase->inputs.begin(), phase->inputs.end()), phase->inputs.end());
588 // Allocate samplers for each input.
589 phase->input_samplers.resize(phase->inputs.size());
591 // We added the effects from the output and back, but we need to output
592 // them in topological sort order in the shader.
593 phase->effects = topological_sort(phase->effects);
595 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
596 phase->input_needs_mipmaps = false;
597 for (unsigned i = 0; i < phase->effects.size(); ++i) {
598 Node *node = phase->effects[i];
599 phase->input_needs_mipmaps |= node->effect->needs_mipmaps();
601 for (unsigned i = 0; i < phase->effects.size(); ++i) {
602 Node *node = phase->effects[i];
603 if (node->effect->num_inputs() == 0) {
604 Input *input = static_cast<Input *>(node->effect);
605 assert(!phase->input_needs_mipmaps || input->can_supply_mipmaps());
606 CHECK(input->set_int("needs_mipmaps", phase->input_needs_mipmaps));
610 // Tell each node which phase it ended up in, so that the unit test
611 // can check that the phases were split in the right place.
612 // Note that this ignores that effects may be part of multiple phases;
613 // if the unit tests need to test such cases, we'll reconsider.
614 for (unsigned i = 0; i < phase->effects.size(); ++i) {
615 phase->effects[i]->containing_phase = phase;
618 // Actually make the shader for this phase.
619 compile_glsl_program(phase);
621 // Initialize timer objects.
622 if (movit_timer_queries_supported) {
623 glGenQueries(1, &phase->timer_query_object);
624 phase->time_elapsed_ns = 0;
625 phase->num_measured_iterations = 0;
628 assert(completed_effects->count(output) == 0);
629 completed_effects->insert(make_pair(output, phase));
630 phases.push_back(phase);
634 void EffectChain::output_dot(const char *filename)
636 if (movit_debug_level != MOVIT_DEBUG_ON) {
640 FILE *fp = fopen(filename, "w");
646 fprintf(fp, "digraph G {\n");
647 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
648 for (unsigned i = 0; i < nodes.size(); ++i) {
649 // Find out which phase this event belongs to.
650 vector<int> in_phases;
651 for (unsigned j = 0; j < phases.size(); ++j) {
652 const Phase* p = phases[j];
653 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
654 in_phases.push_back(j);
658 if (in_phases.empty()) {
659 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
660 } else if (in_phases.size() == 1) {
661 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
662 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
663 (in_phases[0] % 8) + 1);
665 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
667 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
668 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
669 (in_phases[0] % 8) + 1);
672 char from_node_id[256];
673 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
675 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
676 char to_node_id[256];
677 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
679 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
680 output_dot_edge(fp, from_node_id, to_node_id, labels);
683 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
685 vector<string> labels = get_labels_for_edge(nodes[i], NULL);
686 output_dot_edge(fp, from_node_id, "output", labels);
694 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
696 vector<string> labels;
698 if (to != NULL && to->effect->needs_texture_bounce()) {
699 labels.push_back("needs_bounce");
701 if (from->effect->changes_output_size()) {
702 labels.push_back("resize");
705 switch (from->output_color_space) {
706 case COLORSPACE_INVALID:
707 labels.push_back("spc[invalid]");
709 case COLORSPACE_REC_601_525:
710 labels.push_back("spc[rec601-525]");
712 case COLORSPACE_REC_601_625:
713 labels.push_back("spc[rec601-625]");
719 switch (from->output_gamma_curve) {
721 labels.push_back("gamma[invalid]");
724 labels.push_back("gamma[sRGB]");
726 case GAMMA_REC_601: // and GAMMA_REC_709
727 labels.push_back("gamma[rec601/709]");
733 switch (from->output_alpha_type) {
735 labels.push_back("alpha[invalid]");
738 labels.push_back("alpha[blank]");
740 case ALPHA_POSTMULTIPLIED:
741 labels.push_back("alpha[postmult]");
750 void EffectChain::output_dot_edge(FILE *fp,
751 const string &from_node_id,
752 const string &to_node_id,
753 const vector<string> &labels)
755 if (labels.empty()) {
756 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
758 string label = labels[0];
759 for (unsigned k = 1; k < labels.size(); ++k) {
760 label += ", " + labels[k];
762 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
766 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
768 unsigned scaled_width, scaled_height;
770 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
771 // Same aspect, or W/H > aspect (image is wider than the frame).
772 // In either case, keep width, and adjust height.
773 scaled_width = width;
774 scaled_height = lrintf(width * aspect_denom / aspect_nom);
776 // W/H < aspect (image is taller than the frame), so keep height,
778 scaled_width = lrintf(height * aspect_nom / aspect_denom);
779 scaled_height = height;
782 // We should be consistently larger or smaller then the existing choice,
783 // since we have the same aspect.
784 assert(!(scaled_width < *output_width && scaled_height > *output_height));
785 assert(!(scaled_height < *output_height && scaled_width > *output_width));
787 if (scaled_width >= *output_width && scaled_height >= *output_height) {
788 *output_width = scaled_width;
789 *output_height = scaled_height;
793 // Propagate input texture sizes throughout, and inform effects downstream.
794 // (Like a lot of other code, we depend on effects being in topological order.)
795 void EffectChain::inform_input_sizes(Phase *phase)
797 // All effects that have a defined size (inputs and RTT inputs)
798 // get that. Reset all others.
799 for (unsigned i = 0; i < phase->effects.size(); ++i) {
800 Node *node = phase->effects[i];
801 if (node->effect->num_inputs() == 0) {
802 Input *input = static_cast<Input *>(node->effect);
803 node->output_width = input->get_width();
804 node->output_height = input->get_height();
805 assert(node->output_width != 0);
806 assert(node->output_height != 0);
808 node->output_width = node->output_height = 0;
811 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
812 Phase *input = phase->inputs[i];
813 input->output_node->output_width = input->virtual_output_width;
814 input->output_node->output_height = input->virtual_output_height;
815 assert(input->output_node->output_width != 0);
816 assert(input->output_node->output_height != 0);
819 // Now propagate from the inputs towards the end, and inform as we go.
820 // The rules are simple:
822 // 1. Don't touch effects that already have given sizes (ie., inputs
823 // or effects that change the output size).
824 // 2. If all of your inputs have the same size, that will be your output size.
825 // 3. Otherwise, your output size is 0x0.
826 for (unsigned i = 0; i < phase->effects.size(); ++i) {
827 Node *node = phase->effects[i];
828 if (node->effect->num_inputs() == 0) {
831 unsigned this_output_width = 0;
832 unsigned this_output_height = 0;
833 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
834 Node *input = node->incoming_links[j];
835 node->effect->inform_input_size(j, input->output_width, input->output_height);
837 this_output_width = input->output_width;
838 this_output_height = input->output_height;
839 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
841 this_output_width = 0;
842 this_output_height = 0;
845 if (node->effect->changes_output_size()) {
846 // We cannot call get_output_size() before we've done inform_input_size()
848 unsigned real_width, real_height;
849 node->effect->get_output_size(&real_width, &real_height,
850 &node->output_width, &node->output_height);
851 assert(node->effect->sets_virtual_output_size() ||
852 (real_width == node->output_width &&
853 real_height == node->output_height));
855 node->output_width = this_output_width;
856 node->output_height = this_output_height;
861 // Note: You should call inform_input_sizes() before this, as the last effect's
862 // desired output size might change based on the inputs.
863 void EffectChain::find_output_size(Phase *phase)
865 Node *output_node = phase->effects.back();
867 // If the last effect explicitly sets an output size, use that.
868 if (output_node->effect->changes_output_size()) {
869 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
870 &phase->virtual_output_width, &phase->virtual_output_height);
871 assert(output_node->effect->sets_virtual_output_size() ||
872 (phase->output_width == phase->virtual_output_width &&
873 phase->output_height == phase->virtual_output_height));
877 // If all effects have the same size, use that.
878 unsigned output_width = 0, output_height = 0;
879 bool all_inputs_same_size = true;
881 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
882 Phase *input = phase->inputs[i];
883 assert(input->output_width != 0);
884 assert(input->output_height != 0);
885 if (output_width == 0 && output_height == 0) {
886 output_width = input->virtual_output_width;
887 output_height = input->virtual_output_height;
888 } else if (output_width != input->virtual_output_width ||
889 output_height != input->virtual_output_height) {
890 all_inputs_same_size = false;
893 for (unsigned i = 0; i < phase->effects.size(); ++i) {
894 Effect *effect = phase->effects[i]->effect;
895 if (effect->num_inputs() != 0) {
899 Input *input = static_cast<Input *>(effect);
900 if (output_width == 0 && output_height == 0) {
901 output_width = input->get_width();
902 output_height = input->get_height();
903 } else if (output_width != input->get_width() ||
904 output_height != input->get_height()) {
905 all_inputs_same_size = false;
909 if (all_inputs_same_size) {
910 assert(output_width != 0);
911 assert(output_height != 0);
912 phase->virtual_output_width = phase->output_width = output_width;
913 phase->virtual_output_height = phase->output_height = output_height;
917 // If not, fit all the inputs into the current aspect, and select the largest one.
920 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
921 Phase *input = phase->inputs[i];
922 assert(input->output_width != 0);
923 assert(input->output_height != 0);
924 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
926 for (unsigned i = 0; i < phase->effects.size(); ++i) {
927 Effect *effect = phase->effects[i]->effect;
928 if (effect->num_inputs() != 0) {
932 Input *input = static_cast<Input *>(effect);
933 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
935 assert(output_width != 0);
936 assert(output_height != 0);
937 phase->virtual_output_width = phase->output_width = output_width;
938 phase->virtual_output_height = phase->output_height = output_height;
941 void EffectChain::sort_all_nodes_topologically()
943 nodes = topological_sort(nodes);
946 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
948 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
949 vector<Node *> sorted_list;
950 for (unsigned i = 0; i < nodes.size(); ++i) {
951 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
953 reverse(sorted_list.begin(), sorted_list.end());
957 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
959 if (nodes_left_to_visit->count(node) == 0) {
962 nodes_left_to_visit->erase(node);
963 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
964 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
966 sorted_list->push_back(node);
969 void EffectChain::find_color_spaces_for_inputs()
971 for (unsigned i = 0; i < nodes.size(); ++i) {
972 Node *node = nodes[i];
973 if (node->disabled) {
976 if (node->incoming_links.size() == 0) {
977 Input *input = static_cast<Input *>(node->effect);
978 node->output_color_space = input->get_color_space();
979 node->output_gamma_curve = input->get_gamma_curve();
981 Effect::AlphaHandling alpha_handling = input->alpha_handling();
982 switch (alpha_handling) {
983 case Effect::OUTPUT_BLANK_ALPHA:
984 node->output_alpha_type = ALPHA_BLANK;
986 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
987 node->output_alpha_type = ALPHA_PREMULTIPLIED;
989 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
990 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
992 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
993 case Effect::DONT_CARE_ALPHA_TYPE:
998 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
999 assert(node->output_gamma_curve == GAMMA_LINEAR);
1005 // Propagate gamma and color space information as far as we can in the graph.
1006 // The rules are simple: Anything where all the inputs agree, get that as
1007 // output as well. Anything else keeps having *_INVALID.
1008 void EffectChain::propagate_gamma_and_color_space()
1010 // We depend on going through the nodes in order.
1011 sort_all_nodes_topologically();
1013 for (unsigned i = 0; i < nodes.size(); ++i) {
1014 Node *node = nodes[i];
1015 if (node->disabled) {
1018 assert(node->incoming_links.size() == node->effect->num_inputs());
1019 if (node->incoming_links.size() == 0) {
1020 assert(node->output_color_space != COLORSPACE_INVALID);
1021 assert(node->output_gamma_curve != GAMMA_INVALID);
1025 Colorspace color_space = node->incoming_links[0]->output_color_space;
1026 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1027 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1028 if (node->incoming_links[j]->output_color_space != color_space) {
1029 color_space = COLORSPACE_INVALID;
1031 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1032 gamma_curve = GAMMA_INVALID;
1036 // The conversion effects already have their outputs set correctly,
1037 // so leave them alone.
1038 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1039 node->output_color_space = color_space;
1041 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1042 node->effect->effect_type_id() != "GammaExpansionEffect") {
1043 node->output_gamma_curve = gamma_curve;
1048 // Propagate alpha information as far as we can in the graph.
1049 // Similar to propagate_gamma_and_color_space().
1050 void EffectChain::propagate_alpha()
1052 // We depend on going through the nodes in order.
1053 sort_all_nodes_topologically();
1055 for (unsigned i = 0; i < nodes.size(); ++i) {
1056 Node *node = nodes[i];
1057 if (node->disabled) {
1060 assert(node->incoming_links.size() == node->effect->num_inputs());
1061 if (node->incoming_links.size() == 0) {
1062 assert(node->output_alpha_type != ALPHA_INVALID);
1066 // The alpha multiplication/division effects are special cases.
1067 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1068 assert(node->incoming_links.size() == 1);
1069 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1070 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1073 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1074 assert(node->incoming_links.size() == 1);
1075 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1076 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1080 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1081 // because they are the only one that _need_ postmultiplied alpha.
1082 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1083 node->effect->effect_type_id() == "GammaExpansionEffect") {
1084 assert(node->incoming_links.size() == 1);
1085 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1086 node->output_alpha_type = ALPHA_BLANK;
1087 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1088 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1090 node->output_alpha_type = ALPHA_INVALID;
1095 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1096 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1097 // taken care of above. Rationale: Even if you could imagine
1098 // e.g. an effect that took in an image and set alpha=1.0
1099 // unconditionally, it wouldn't make any sense to have it as
1100 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1101 // got its input pre- or postmultiplied, so it wouldn't know
1102 // whether to divide away the old alpha or not.
1103 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1104 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1105 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1106 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1108 // If the node has multiple inputs, check that they are all valid and
1110 bool any_invalid = false;
1111 bool any_premultiplied = false;
1112 bool any_postmultiplied = false;
1114 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1115 switch (node->incoming_links[j]->output_alpha_type) {
1120 // Blank is good as both pre- and postmultiplied alpha,
1121 // so just ignore it.
1123 case ALPHA_PREMULTIPLIED:
1124 any_premultiplied = true;
1126 case ALPHA_POSTMULTIPLIED:
1127 any_postmultiplied = true;
1135 node->output_alpha_type = ALPHA_INVALID;
1139 // Inputs must be of the same type.
1140 if (any_premultiplied && any_postmultiplied) {
1141 node->output_alpha_type = ALPHA_INVALID;
1145 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1146 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1147 // If the effect has asked for premultiplied alpha, check that it has got it.
1148 if (any_postmultiplied) {
1149 node->output_alpha_type = ALPHA_INVALID;
1150 } else if (!any_premultiplied &&
1151 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1152 // Blank input alpha, and the effect preserves blank alpha.
1153 node->output_alpha_type = ALPHA_BLANK;
1155 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1158 // OK, all inputs are the same, and this effect is not going
1160 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1161 if (any_premultiplied) {
1162 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1163 } else if (any_postmultiplied) {
1164 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1166 node->output_alpha_type = ALPHA_BLANK;
1172 bool EffectChain::node_needs_colorspace_fix(Node *node)
1174 if (node->disabled) {
1177 if (node->effect->num_inputs() == 0) {
1181 // propagate_gamma_and_color_space() has already set our output
1182 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1183 if (node->output_color_space == COLORSPACE_INVALID) {
1186 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1189 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1190 // the graph. Our strategy is not always optimal, but quite simple:
1191 // Find an effect that's as early as possible where the inputs are of
1192 // unacceptable colorspaces (that is, either different, or, if the effect only
1193 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1194 // propagate the information anew, and repeat until there are no more such
1196 void EffectChain::fix_internal_color_spaces()
1198 unsigned colorspace_propagation_pass = 0;
1202 for (unsigned i = 0; i < nodes.size(); ++i) {
1203 Node *node = nodes[i];
1204 if (!node_needs_colorspace_fix(node)) {
1208 // Go through each input that is not sRGB, and insert
1209 // a colorspace conversion after it.
1210 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1211 Node *input = node->incoming_links[j];
1212 assert(input->output_color_space != COLORSPACE_INVALID);
1213 if (input->output_color_space == COLORSPACE_sRGB) {
1216 Node *conversion = add_node(new ColorspaceConversionEffect());
1217 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1218 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1219 conversion->output_color_space = COLORSPACE_sRGB;
1220 replace_sender(input, conversion);
1221 connect_nodes(input, conversion);
1224 // Re-sort topologically, and propagate the new information.
1225 propagate_gamma_and_color_space();
1232 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1233 output_dot(filename);
1234 assert(colorspace_propagation_pass < 100);
1235 } while (found_any);
1237 for (unsigned i = 0; i < nodes.size(); ++i) {
1238 Node *node = nodes[i];
1239 if (node->disabled) {
1242 assert(node->output_color_space != COLORSPACE_INVALID);
1246 bool EffectChain::node_needs_alpha_fix(Node *node)
1248 if (node->disabled) {
1252 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1253 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1254 return (node->output_alpha_type == ALPHA_INVALID);
1257 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1258 // the graph. Similar to fix_internal_color_spaces().
1259 void EffectChain::fix_internal_alpha(unsigned step)
1261 unsigned alpha_propagation_pass = 0;
1265 for (unsigned i = 0; i < nodes.size(); ++i) {
1266 Node *node = nodes[i];
1267 if (!node_needs_alpha_fix(node)) {
1271 // If we need to fix up GammaExpansionEffect, then clearly something
1272 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1274 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1276 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1278 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1279 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1280 assert(node->incoming_links.size() == 1);
1281 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1282 desired_type = ALPHA_POSTMULTIPLIED;
1285 // Go through each input that is not premultiplied alpha, and insert
1286 // a conversion before it.
1287 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1288 Node *input = node->incoming_links[j];
1289 assert(input->output_alpha_type != ALPHA_INVALID);
1290 if (input->output_alpha_type == desired_type ||
1291 input->output_alpha_type == ALPHA_BLANK) {
1295 if (desired_type == ALPHA_PREMULTIPLIED) {
1296 conversion = add_node(new AlphaMultiplicationEffect());
1298 conversion = add_node(new AlphaDivisionEffect());
1300 conversion->output_alpha_type = desired_type;
1301 replace_sender(input, conversion);
1302 connect_nodes(input, conversion);
1305 // Re-sort topologically, and propagate the new information.
1306 propagate_gamma_and_color_space();
1314 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1315 output_dot(filename);
1316 assert(alpha_propagation_pass < 100);
1317 } while (found_any);
1319 for (unsigned i = 0; i < nodes.size(); ++i) {
1320 Node *node = nodes[i];
1321 if (node->disabled) {
1324 assert(node->output_alpha_type != ALPHA_INVALID);
1328 // Make so that the output is in the desired color space.
1329 void EffectChain::fix_output_color_space()
1331 Node *output = find_output_node();
1332 if (output->output_color_space != output_format.color_space) {
1333 Node *conversion = add_node(new ColorspaceConversionEffect());
1334 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1335 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1336 conversion->output_color_space = output_format.color_space;
1337 connect_nodes(output, conversion);
1339 propagate_gamma_and_color_space();
1343 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1344 void EffectChain::fix_output_alpha()
1346 Node *output = find_output_node();
1347 assert(output->output_alpha_type != ALPHA_INVALID);
1348 if (output->output_alpha_type == ALPHA_BLANK) {
1349 // No alpha output, so we don't care.
1352 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1353 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1354 Node *conversion = add_node(new AlphaDivisionEffect());
1355 connect_nodes(output, conversion);
1357 propagate_gamma_and_color_space();
1359 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1360 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1361 Node *conversion = add_node(new AlphaMultiplicationEffect());
1362 connect_nodes(output, conversion);
1364 propagate_gamma_and_color_space();
1368 bool EffectChain::node_needs_gamma_fix(Node *node)
1370 if (node->disabled) {
1374 // Small hack since the output is not an explicit node:
1375 // If we are the last node and our output is in the wrong
1376 // space compared to EffectChain's output, we need to fix it.
1377 // This will only take us to linear, but fix_output_gamma()
1378 // will come and take us to the desired output gamma
1381 // This needs to be before everything else, since it could
1382 // even apply to inputs (if they are the only effect).
1383 if (node->outgoing_links.empty() &&
1384 node->output_gamma_curve != output_format.gamma_curve &&
1385 node->output_gamma_curve != GAMMA_LINEAR) {
1389 if (node->effect->num_inputs() == 0) {
1393 // propagate_gamma_and_color_space() has already set our output
1394 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1395 // except for GammaCompressionEffect.
1396 if (node->output_gamma_curve == GAMMA_INVALID) {
1399 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1400 assert(node->incoming_links.size() == 1);
1401 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1404 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1407 // Very similar to fix_internal_color_spaces(), but for gamma.
1408 // There is one difference, though; before we start adding conversion nodes,
1409 // we see if we can get anything out of asking the sources to deliver
1410 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1411 // does that part, while fix_internal_gamma_by_inserting_nodes()
1412 // inserts nodes as needed afterwards.
1413 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1415 unsigned gamma_propagation_pass = 0;
1419 for (unsigned i = 0; i < nodes.size(); ++i) {
1420 Node *node = nodes[i];
1421 if (!node_needs_gamma_fix(node)) {
1425 // See if all inputs can give us linear gamma. If not, leave it.
1426 vector<Node *> nonlinear_inputs;
1427 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1428 assert(!nonlinear_inputs.empty());
1431 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1432 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1433 all_ok &= input->can_output_linear_gamma();
1440 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1441 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1442 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1445 // Re-sort topologically, and propagate the new information.
1446 propagate_gamma_and_color_space();
1453 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1454 output_dot(filename);
1455 assert(gamma_propagation_pass < 100);
1456 } while (found_any);
1459 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1461 unsigned gamma_propagation_pass = 0;
1465 for (unsigned i = 0; i < nodes.size(); ++i) {
1466 Node *node = nodes[i];
1467 if (!node_needs_gamma_fix(node)) {
1471 // Special case: We could be an input and still be asked to
1472 // fix our gamma; if so, we should be the only node
1473 // (as node_needs_gamma_fix() would only return true in
1474 // for an input in that case). That means we should insert
1475 // a conversion node _after_ ourselves.
1476 if (node->incoming_links.empty()) {
1477 assert(node->outgoing_links.empty());
1478 Node *conversion = add_node(new GammaExpansionEffect());
1479 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1480 conversion->output_gamma_curve = GAMMA_LINEAR;
1481 connect_nodes(node, conversion);
1484 // If not, go through each input that is not linear gamma,
1485 // and insert a gamma conversion after it.
1486 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1487 Node *input = node->incoming_links[j];
1488 assert(input->output_gamma_curve != GAMMA_INVALID);
1489 if (input->output_gamma_curve == GAMMA_LINEAR) {
1492 Node *conversion = add_node(new GammaExpansionEffect());
1493 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1494 conversion->output_gamma_curve = GAMMA_LINEAR;
1495 replace_sender(input, conversion);
1496 connect_nodes(input, conversion);
1499 // Re-sort topologically, and propagate the new information.
1501 propagate_gamma_and_color_space();
1508 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1509 output_dot(filename);
1510 assert(gamma_propagation_pass < 100);
1511 } while (found_any);
1513 for (unsigned i = 0; i < nodes.size(); ++i) {
1514 Node *node = nodes[i];
1515 if (node->disabled) {
1518 assert(node->output_gamma_curve != GAMMA_INVALID);
1522 // Make so that the output is in the desired gamma.
1523 // Note that this assumes linear input gamma, so it might create the need
1524 // for another pass of fix_internal_gamma().
1525 void EffectChain::fix_output_gamma()
1527 Node *output = find_output_node();
1528 if (output->output_gamma_curve != output_format.gamma_curve) {
1529 Node *conversion = add_node(new GammaCompressionEffect());
1530 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1531 conversion->output_gamma_curve = output_format.gamma_curve;
1532 connect_nodes(output, conversion);
1536 // If the user has requested Y'CbCr output, we need to do this conversion
1537 // _after_ GammaCompressionEffect etc., but before dither (see below).
1538 // This is because Y'CbCr, with the exception of a special optional mode
1539 // in Rec. 2020 (which we currently don't support), is defined to work on
1540 // gamma-encoded data.
1541 void EffectChain::add_ycbcr_conversion_if_needed()
1543 assert(output_color_rgba || output_color_ycbcr);
1544 if (!output_color_ycbcr) {
1547 Node *output = find_output_node();
1548 Node *ycbcr = add_node(new YCbCrConversionEffect(output_ycbcr_format));
1549 connect_nodes(output, ycbcr);
1552 // If the user has requested dither, add a DitherEffect right at the end
1553 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1554 // since dither is about the only effect that can _not_ be done in linear space.
1555 void EffectChain::add_dither_if_needed()
1557 if (num_dither_bits == 0) {
1560 Node *output = find_output_node();
1561 Node *dither = add_node(new DitherEffect());
1562 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1563 connect_nodes(output, dither);
1565 dither_effect = dither->effect;
1568 // Find the output node. This is, simply, one that has no outgoing links.
1569 // If there are multiple ones, the graph is malformed (we do not support
1570 // multiple outputs right now).
1571 Node *EffectChain::find_output_node()
1573 vector<Node *> output_nodes;
1574 for (unsigned i = 0; i < nodes.size(); ++i) {
1575 Node *node = nodes[i];
1576 if (node->disabled) {
1579 if (node->outgoing_links.empty()) {
1580 output_nodes.push_back(node);
1583 assert(output_nodes.size() == 1);
1584 return output_nodes[0];
1587 void EffectChain::finalize()
1589 // Output the graph as it is before we do any conversions on it.
1590 output_dot("step0-start.dot");
1592 // Give each effect in turn a chance to rewrite its own part of the graph.
1593 // Note that if more effects are added as part of this, they will be
1594 // picked up as part of the same for loop, since they are added at the end.
1595 for (unsigned i = 0; i < nodes.size(); ++i) {
1596 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1598 output_dot("step1-rewritten.dot");
1600 find_color_spaces_for_inputs();
1601 output_dot("step2-input-colorspace.dot");
1604 output_dot("step3-propagated-alpha.dot");
1606 propagate_gamma_and_color_space();
1607 output_dot("step4-propagated-all.dot");
1609 fix_internal_color_spaces();
1610 fix_internal_alpha(6);
1611 fix_output_color_space();
1612 output_dot("step7-output-colorspacefix.dot");
1614 output_dot("step8-output-alphafix.dot");
1616 // Note that we need to fix gamma after colorspace conversion,
1617 // because colorspace conversions might create needs for gamma conversions.
1618 // Also, we need to run an extra pass of fix_internal_gamma() after
1619 // fixing the output gamma, as we only have conversions to/from linear,
1620 // and fix_internal_alpha() since GammaCompressionEffect needs
1621 // postmultiplied input.
1622 fix_internal_gamma_by_asking_inputs(9);
1623 fix_internal_gamma_by_inserting_nodes(10);
1625 output_dot("step11-output-gammafix.dot");
1627 output_dot("step12-output-alpha-propagated.dot");
1628 fix_internal_alpha(13);
1629 output_dot("step14-output-alpha-fixed.dot");
1630 fix_internal_gamma_by_asking_inputs(15);
1631 fix_internal_gamma_by_inserting_nodes(16);
1633 output_dot("step17-before-ycbcr.dot");
1634 add_ycbcr_conversion_if_needed();
1636 output_dot("step18-before-dither.dot");
1637 add_dither_if_needed();
1639 output_dot("step19-final.dot");
1641 // Construct all needed GLSL programs, starting at the output.
1642 // We need to keep track of which effects have already been computed,
1643 // as an effect with multiple users could otherwise be calculated
1645 map<Node *, Phase *> completed_effects;
1646 construct_phase(find_output_node(), &completed_effects);
1648 output_dot("step20-split-to-phases.dot");
1650 assert(phases[0]->inputs.empty());
1655 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1659 // This needs to be set anew, in case we are coming from a different context
1660 // from when we initialized.
1662 glDisable(GL_DITHER);
1665 // Save original viewport.
1666 GLuint x = 0, y = 0;
1668 if (width == 0 && height == 0) {
1670 glGetIntegerv(GL_VIEWPORT, viewport);
1673 width = viewport[2];
1674 height = viewport[3];
1679 glDisable(GL_BLEND);
1681 glDisable(GL_DEPTH_TEST);
1683 glDepthMask(GL_FALSE);
1686 // Generate a VAO. All the phases should have exactly the same vertex attributes,
1687 // so it's safe to reuse this.
1688 float vertices[] = {
1695 glGenVertexArrays(1, &vao);
1697 glBindVertexArray(vao);
1700 GLuint position_vbo = fill_vertex_attribute(phases[0]->glsl_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
1701 GLuint texcoord_vbo = fill_vertex_attribute(phases[0]->glsl_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
1703 set<Phase *> generated_mipmaps;
1705 // We choose the simplest option of having one texture per output,
1706 // since otherwise this turns into an (albeit simple) register allocation problem.
1707 map<Phase *, GLuint> output_textures;
1709 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1710 Phase *phase = phases[phase_num];
1712 if (do_phase_timing) {
1713 glBeginQuery(GL_TIME_ELAPSED, phase->timer_query_object);
1715 if (phase_num == phases.size() - 1) {
1716 // Last phase goes to the output the user specified.
1717 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
1719 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
1720 assert(status == GL_FRAMEBUFFER_COMPLETE);
1721 glViewport(x, y, width, height);
1722 if (dither_effect != NULL) {
1723 CHECK(dither_effect->set_int("output_width", width));
1724 CHECK(dither_effect->set_int("output_height", height));
1727 execute_phase(phase, phase_num == phases.size() - 1, &output_textures, &generated_mipmaps);
1728 if (do_phase_timing) {
1729 glEndQuery(GL_TIME_ELAPSED);
1733 for (map<Phase *, GLuint>::const_iterator texture_it = output_textures.begin();
1734 texture_it != output_textures.end();
1736 resource_pool->release_2d_texture(texture_it->second);
1739 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1744 cleanup_vertex_attribute(phases[0]->glsl_program_num, "position", position_vbo);
1745 cleanup_vertex_attribute(phases[0]->glsl_program_num, "texcoord", texcoord_vbo);
1747 glDeleteVertexArrays(1, &vao);
1750 if (do_phase_timing) {
1751 // Get back the timer queries.
1752 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1753 Phase *phase = phases[phase_num];
1754 GLint available = 0;
1755 while (!available) {
1756 glGetQueryObjectiv(phase->timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
1758 GLuint64 time_elapsed;
1759 glGetQueryObjectui64v(phase->timer_query_object, GL_QUERY_RESULT, &time_elapsed);
1760 phase->time_elapsed_ns += time_elapsed;
1761 ++phase->num_measured_iterations;
1766 void EffectChain::enable_phase_timing(bool enable)
1769 assert(movit_timer_queries_supported);
1771 this->do_phase_timing = enable;
1774 void EffectChain::reset_phase_timing()
1776 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1777 Phase *phase = phases[phase_num];
1778 phase->time_elapsed_ns = 0;
1779 phase->num_measured_iterations = 0;
1783 void EffectChain::print_phase_timing()
1785 double total_time_ms = 0.0;
1786 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
1787 Phase *phase = phases[phase_num];
1788 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
1789 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
1790 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
1791 if (effect_num != 0) {
1794 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
1797 total_time_ms += avg_time_ms;
1799 printf("Total: %5.1f ms\n", total_time_ms);
1802 void EffectChain::execute_phase(Phase *phase, bool last_phase, map<Phase *, GLuint> *output_textures, set<Phase *> *generated_mipmaps)
1806 // Find a texture for this phase.
1807 inform_input_sizes(phase);
1809 find_output_size(phase);
1811 GLuint tex_num = resource_pool->create_2d_texture(GL_RGBA16F, phase->output_width, phase->output_height);
1812 output_textures->insert(make_pair(phase, tex_num));
1815 const GLuint glsl_program_num = phase->glsl_program_num;
1817 glUseProgram(glsl_program_num);
1820 // Set up RTT inputs for this phase.
1821 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
1822 glActiveTexture(GL_TEXTURE0 + sampler);
1823 Phase *input = phase->inputs[sampler];
1824 input->output_node->bound_sampler_num = sampler;
1825 glBindTexture(GL_TEXTURE_2D, (*output_textures)[input]);
1827 if (phase->input_needs_mipmaps && generated_mipmaps->count(input) == 0) {
1828 glGenerateMipmap(GL_TEXTURE_2D);
1830 generated_mipmaps->insert(input);
1832 setup_rtt_sampler(sampler, phase->input_needs_mipmaps);
1833 phase->input_samplers[sampler] = sampler; // Bind the sampler to the right uniform.
1836 // And now the output. (Already set up for us if it is the last phase.)
1838 fbo = resource_pool->create_fbo((*output_textures)[phase]);
1839 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1840 glViewport(0, 0, phase->output_width, phase->output_height);
1843 // Give the required parameters to all the effects.
1844 unsigned sampler_num = phase->inputs.size();
1845 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1846 Node *node = phase->effects[i];
1847 unsigned old_sampler_num = sampler_num;
1848 node->effect->set_gl_state(glsl_program_num, phase->effect_ids[node], &sampler_num);
1851 if (node->effect->is_single_texture()) {
1852 assert(sampler_num - old_sampler_num == 1);
1853 node->bound_sampler_num = old_sampler_num;
1855 node->bound_sampler_num = -1;
1859 // Uniforms need to come after set_gl_state(), since they can be updated
1861 setup_uniforms(phase);
1863 glDrawArrays(GL_TRIANGLES, 0, 3);
1869 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1870 Node *node = phase->effects[i];
1871 node->effect->clear_gl_state();
1875 resource_pool->release_fbo(fbo);
1879 void EffectChain::setup_uniforms(Phase *phase)
1881 // TODO: Use UBO blocks.
1882 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
1883 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
1884 if (uniform.location != -1) {
1885 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1888 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
1889 const Uniform<bool> &uniform = phase->uniforms_bool[i];
1890 assert(uniform.num_values == 1);
1891 if (uniform.location != -1) {
1892 glUniform1i(uniform.location, *uniform.value);
1895 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
1896 const Uniform<int> &uniform = phase->uniforms_int[i];
1897 if (uniform.location != -1) {
1898 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
1901 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
1902 const Uniform<float> &uniform = phase->uniforms_float[i];
1903 if (uniform.location != -1) {
1904 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
1907 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
1908 const Uniform<float> &uniform = phase->uniforms_vec2[i];
1909 if (uniform.location != -1) {
1910 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
1913 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
1914 const Uniform<float> &uniform = phase->uniforms_vec3[i];
1915 if (uniform.location != -1) {
1916 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
1919 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
1920 const Uniform<float> &uniform = phase->uniforms_vec4[i];
1921 if (uniform.location != -1) {
1922 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
1925 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
1926 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
1927 assert(uniform.num_values == 1);
1928 if (uniform.location != -1) {
1929 // Convert to float (GLSL has no double matrices).
1931 for (unsigned y = 0; y < 3; ++y) {
1932 for (unsigned x = 0; x < 3; ++x) {
1933 matrixf[y + x * 3] = (*uniform.value)(y, x);
1936 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
1941 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
1943 glActiveTexture(GL_TEXTURE0 + sampler_num);
1946 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1949 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1952 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1954 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1958 } // namespace movit